Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monolog - logging only specific level of errors

Tags:

php

monolog

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?

like image 522
Jan Richter Avatar asked Jan 29 '26 03:01

Jan Richter


1 Answers

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);
like image 94
Andrew Berridge Avatar answered Jan 31 '26 17:01

Andrew Berridge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!