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
?
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
Set bubble
param to false
$logger->pushHandler(new StreamHandler(__DIR__.'/log/info.log', Logger::INFO, false));
来源:https://stackoverflow.com/questions/47091476/monolog-logging-only-specific-level-of-errors