Since a few years, you can use the PSR-3 LoggerInterface in MediaWiki to log messages. But how can you tell MediaWiki to use a specific logger? In this technical post, we will look at how to use a Monolog logger in MediaWiki.
If you have used Monolog before, you presumably know how to create a logger and add handlers to it. Most people configure MediaWiki logging using $wgDebugLogGroups. This config however does not allow us to inject our (Monolog) Logger instance into MediaWiki.
Instead, you can use $wgMWLoggerDefaultSpi, which specifies a service that creates the loggers MediaWiki uses. You could use the MonologSpi that MediaWiki provides. But as you can see on the MonologSpi documentation, the standard MediaWiki approach here might not align with your expectations. There is no way to inject your Logger instance created via the standard Monolog approach.
We can get around this by creating our own mini Spi implementation. In this implementation, you can either create (and cache) the Logger or take an existing Logger instance. The below copy-pastable example shows how to configure MediaWiki to use an existing Logger instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$logger = new \Monolog\Logger('name'); $logger->pushHandler( new \Monolog\Handler\StreamHandler( __DIR__ . '/cache/error.log', \Monolog\Logger::ERROR ) ); $wgMWLoggerDefaultSpi = [ 'factory' => function() use ( $logger ): \MediaWiki\Logger\Spi { return new class ( $logger ) implements \MediaWiki\Logger\Spi { private \Monolog\Logger $logger; public function __construct( \Monolog\Logger $logger ) { $this->logger = $logger; } public function getLogger( $channel ) { return $this->logger->withName( $channel ); } }; } ]; |
Since you construct the Logger yourself, you can configure it as you like, with all the tools available in the Monolog ecosystem.
The above example uses PHP 7.4.