Magento 2: Can you use a Plugin with the `Psr\Log\LoggerInterface` type?
-
13-12-2019 - |
Question
I've got a di.xml that looks something like this
<config>
<type name="Psr\Log\LoggerInterface">
<plugin name="namespace_modulename_plugins_psr"
type="Namespace\Modulename\Plugins\Psr"
sortOrder="10"
disabled="false"/>
</type>
</config>
The Namespace\Modulename\Plugins\Psr
class can be instantiated, and has a beforeInfo
method defined
public function beforeInfo($subject)
{
var_dump(__METHOD__);
exit;
}
However, if I inject a logger and try to use it
/* @var $psr `Psr\Log\LoggerInterface` */
$psr->info("This is a message");
The message will successfully log, but the system does not call my plugin method.
Is there something special about the Psr\Log\LoggerInterface
that makes in non-plugin-able? If not, does anyone have a solid methodology for debugging plugin configuration issues?
Solution 2
After a bit of research, it turns out the Psr\Log\LoggerInterface
(and its underlying concrete Monolog
implementation class) can be plugged into. The problem was, if you have developer mode enabled you need to do a full di compile (see this bug). Running
php bin/magento setup:di:compile
should get the interceptors generated, and the plugins working.
OTHER TIPS
PSR\Log\LoggerInterface
is not in magento module or framework folder. So it's not analyzed by compiler and will not be pluginized in production mode. If you want to pluginize/configure behavior of third-party classes, you should use adapter.