phpmonolog

Monolog - logging only specific level of errors


I am using Monolog in vanilla PHP application.

I'd like to log errors of only specific level - INFO and not above, since I have other handlers for that.

Here's my code:

<?php
$logger = new Logger('mylogger');
$logger->pushHandler(new StreamHandler(__DIR__.'/log/errors.log', Logger::WARNING));
$logger->pushHandler(new StreamHandler(__DIR__.'/log/info.log', Logger::INFO));

Is there any way to log just INFO mesages to info.log?


Solution

  • I had the same issue today which brought me to here. Anyway I solved it by using Monologs FilterHandler.

    The FilterHandler allows you to pass in another handler as an argument, and then specify the min and max logging levels that will trigger that handler.

    There are a few other handlers that can be useful in specific situations.

    // Create the logging instance
    $logger = new \Monolog\Logger('myLogger');
    
    // Create error stream handler for error events and higher
    $errorStreamHandler = new \Monolog\Handler\StreamHandler(
        'Some/DirectoryPath/error.log',
        \Monolog\Logger::ERROR);
    
    // Create info stream handler for info events and higher
    $infoStreamHandler = new \Monolog\Handler\StreamHandler(
        'Some/DirectoryPath/Info.log',
        \Monolog\Logger::INFO);
    
    // Create filter handler to make sure info stream only logs info events
    // Pass in the info handler 
    // Debug is the minimum level this handler will handle
    // Info is the maximum level this handler will handle
    $infoFilterHandler = new \Monolog\Handler\FilterHandler(
        $infoStreamHandler,
        \Monolog\Logger::DEBUG,
        \Monolog\Logger::INFO);
    
    // Add the handlers to logger
    $logger->pushHandler($errorStreamHandler);
    $logger->pushHandler($infoFilterHandler);
    
    // Yay no errors in Info.log
    $logger->addError("Some Error");
    $logger->addInfo("Some Info");
    

    Update Ali Refer to the source code of \Monolog\Level to look up what constants are available then assign the constant to a variable.

    $someVar = \Monolog\Level::Info;
    
    $infoStreamHandler = new \Monolog\Handler\StreamHandler(
        'Some/DirectoryPath/Info.log',
        $someVar);