Quantcast
Channel: MediaWiki – Entropy Wins
Viewing all articles
Browse latest Browse all 28

Using PSR-3 Monolog in MediaWiki

$
0
0

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 line up 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 you can take an existing Loger instance. The below copy-pastable example shows how to configure MediaWiki to use an existing Logger instance.

$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.

The post Using PSR-3 Monolog in MediaWiki appeared first on Entropy Wins.


Viewing all articles
Browse latest Browse all 28

Latest Images

Trending Articles





Latest Images