Using PSR-3 Monolog in MediaWiki

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.

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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.