Use WPCLIHandler in a command
Use this guide when you already have a WP-CLI command and want to route logs through Monolog.
Steps
- Install the package:
composer require mhcg/monolog-wp-cli- In your command callback, create a logger and attach the handler:
<?php
use Monolog\Level;
use Monolog\Logger;
use MHCG\Monolog\Handler\WPCLIHandler;
function mycommand_command( $args ) {
$logger = new Logger( 'mycommand' );
$logger->pushHandler( new WPCLIHandler( Level::Info ) );
$logger->info( 'Starting' );
$logger->warning( 'Potential issue detected' );
$logger->error( 'Failed to process one item' );
}
WP_CLI::add_command( 'mycommand', 'mycommand_command' );- Optional: if you need pre-v2.2
NOTICEbehaviour (warningoutput), pass a logger-map override:
$logger->pushHandler(
new WPCLIHandler(
Level::Info,
true,
false,
[
Level::Notice->value => [
'method' => 'warning',
'includeLevelName' => true,
],
]
)
);- Optional: if you want Monolog
contextandextradata in output, enable verbose mode:
$logger->pushHandler( new WPCLIHandler( Level::Info, true, true ) );
$logger->notice( 'Processed batch', [ 'batch' => 12 ] );You can also enable the same formatter behaviour through WP_DEBUG.
- Run the command normally:
wp mycommand- Optional: run with debug visibility:
wp mycommand --debug- Optional: run in quiet mode:
wp mycommand --quietNotes
- The handler is intended for WP-CLI runtime. Constructing it outside WP-CLI raises a runtime exception.
- Use the Monolog
Levelenum for handler thresholds and logger-map keys on Monolog 3. debugmessages rely on WP-CLI debug mode.- Monolog
contextandextradata are only shown when the handler is in verbose mode, either via the constructor flag orWP_DEBUG. - From v2.2,
noticemaps toWP_CLI::log()by default. - Error-level output is sent through WP-CLI error handling.