This tutorial walks through a minimal setup that sends Monolog output to WP-CLI.
By the end, you will run a command and see warning and error output through WP-CLI.
composer require mhcg/monolog-wp-cli
Use Monolog with the handler and emit a few levels:
<?php
use Monolog\Logger;
use MHCG\Monolog\Handler\WPCLIHandler;
function mycommand_command( $args ) {
$log = new Logger( 'mycommand' );
$log->pushHandler( new WPCLIHandler( Logger::INFO ) );
$log->debug( 'Only shown with --debug' );
$log->info( 'Started running' );
$log->warning( 'Something happened of note' );
$log->error( 'An error has occurred' );
}
WP_CLI::add_command( 'mycommand', 'mycommand_command' );
wp mycommand
Expected behaviour:
debug is hidden unless --debug is used.info and warning are normal command output.error appears as an error message.wp mycommand --quiet
Expected behaviour:
By default, output uses message-only formatting. To include Monolog context and extra data, enable verbose mode:
$log->pushHandler( new WPCLIHandler( Logger::INFO, true, true ) );
$log->notice( 'Import completed', [ 'items' => 5 ] );
You can also enable verbose output by setting WP_DEBUG to true in the runtime.
If you already have an existing command and only need integration steps, continue with the how-to guide.