Use this guide when you already have a WP-CLI command and want to route logs through Monolog.
composer require mhcg/monolog-wp-cli
<?php
use Monolog\Logger;
use MHCG\Monolog\Handler\WPCLIHandler;
function mycommand_command( $args ) {
$logger = new Logger( 'mycommand' );
$logger->pushHandler( new WPCLIHandler( Logger::INFO ) );
$logger->info( 'Starting' );
$logger->warning( 'Potential issue detected' );
$logger->error( 'Failed to process one item' );
}
WP_CLI::add_command( 'mycommand', 'mycommand_command' );
NOTICE behaviour (warning output), pass a logger-map override:$logger->pushHandler(
new WPCLIHandler(
Logger::INFO,
true,
false,
[
Logger::NOTICE => [
'method' => 'warning',
'includeLevelName' => true,
],
]
)
);
context and extra data in output, enable verbose mode:$logger->pushHandler( new WPCLIHandler( Logger::INFO, true, true ) );
$logger->notice( 'Processed batch', [ 'batch' => 12 ] );
You can also enable the same formatter behaviour through WP_DEBUG.
wp mycommand
wp mycommand --debug
wp mycommand --quiet
debug messages rely on WP-CLI debug mode.context and extra data are only shown when the handler is in verbose mode, either via the constructor flag or WP_DEBUG.notice maps to WP_CLI::log() by default.