Monolog - logging only specific level of errors

时光怂恿深爱的人放手 提交于 2019-12-06 07:35:36

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\Logger to look up what constants are available then assign the constant to a variable.

$someVar = \Monolog\Logger::INFO;

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

Based on @Sasha Vas answer.

Monologs StreamHandler has a bubble parameter which does exactly what you want, avoids the log bubbling up to other levels.

After Laravel 5.6 this undocumented feature is also available.

This is how one of my channels looks like:

'warning' => [
            'driver' => 'single',
            'level' => 'warning',
            'bubble' => false,
            'path' => storage_path('logs/warning.log'),
],

Now, if I use Log::warning('warning') it will only show up in warning.log

Sasha Vas

Set bubble param to false

$logger->pushHandler(new StreamHandler(__DIR__.'/log/info.log', Logger::INFO, false));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!