monolog-wp-cli

How-to: Use WPCLIHandler in a Command

Use this guide when you already have a WP-CLI command and want to route logs through Monolog.

Steps

  1. Install the package:
composer require mhcg/monolog-wp-cli
  1. In your command callback, create a logger and attach the handler:
<?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' );
  1. Optional: if you need pre-v2.2 NOTICE behaviour (warning output), pass a logger-map override:
$logger->pushHandler(
    new WPCLIHandler(
        Logger::INFO,
        true,
        false,
        [
            Logger::NOTICE => [
                'method' => 'warning',
                'includeLevelName' => true,
            ],
        ]
    )
);
  1. Optional: if you want Monolog 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.

  1. Run the command normally:
wp mycommand
  1. Optional: run with debug visibility:
wp mycommand --debug
  1. Optional: run in quiet mode:
wp mycommand --quiet

Notes