简体   繁体   中英

Lumen 5.4 Log info level to separate file

Using Lumen Framework 5.4, I am trying to write Log::info('etc') into a separate file, storage/logs/info.log . However, the code I have found logs log level info and above into the seperate file, while I want just the info log level to be logged into my custom file.

In bootstrap/app.php :

$app->configureMonologUsing(function($monolog) {
    $handler = new Monolog\Handler\StreamHandler(storage_path('logs/info.log'), Monolog\Logger::INFO, false);
    $handler->setFormatter(new \Monolog\Formatter\LineFormatter(null, null, true));

    $monolog->pushHandler($handler);

    return $monolog;
});

How can I make sure that Lumen will log level info into storage/logs/info.log and all other log levels into the default log file, storage/logs/lumen.log ?

You Can use multiple StreamHandlers for handling different level of log.

Try this:- It will log INFO in info.log file & others in logs.log file

$app->configureMonologUsing(function($monolog) {

$infoHandler = new Monolog\Handler\StreamHandler( storage_path("logs/info.log"), Monolog\Logger::INFO, false);
$noticeHandler = new Monolog\Handler\StreamHandler( storage_path("/logs/logs.log"), Monolog\Logger::NOTICE, false);


$monolog->pushHandler($infoHandler);
$monolog->pushHandler($noticeHandler);

$infoHandler->setFormatter(new \Monolog\Formatter\LineFormatter(null, null, true));
$noticeHandler->setFormatter(new \Monolog\Formatter\LineFormatter(null, null, true));

return $monolog;
});

Note:-

One note on that snippet, the order you push the streamhandlers on is important: push the most restrictive on last, so that it is hit first. Otherwise, say if you pushed the infoHandler on last, it would log everything above it also and an error wouldn't make it to the error handler.

So push your handlers in Increasing levels of severity

Source:- Advance Logging with Laravel and Monolog

I had a simliar situation and wanted a seperate log-file for calls to my application done by embedded iframe calls (I provide some widgets to another site)

Found out I was using Lumen version >= 5.6, so I made a custom log channel (By adding logging.php to app/config-dir).

Copied daily channel, and renamed to "widget" along with filename.

Source: Lumen Daily Logs

In my controller I added

use Log;

And I log messages like this also in the controller:

Log::channel('widget')->info('message from custom channel');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM