monolog-wp-cli

Tutorial: First Logger in WP-CLI

This tutorial walks through a minimal setup that sends Monolog output to WP-CLI.

Goal

By the end, you will run a command and see warning and error output through WP-CLI.

Before you start

1. Install the package

composer require mhcg/monolog-wp-cli

2. Create a command callback

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' );

3. Run the command

wp mycommand

Expected behaviour:

4. Check quiet mode

wp mycommand --quiet

Expected behaviour:

5. Enable context output when needed

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.

Next step

If you already have an existing command and only need integration steps, continue with the how-to guide.