简体   繁体   中英

Modify log format on runtime using Monolog and Laravel

I need write a customlog on laravel 5.3, and modify on runtime for add some extra information.

So far I have managed to do it, but the code does not work because what I can do is add a new instance of the log, which duplicates the lines in each modification of the format.

My handicap is that I do not know how to return or if this is possible, the current handler of the logging system, and simply pass it the format modification.

The code below allows me to modify the format line, but only once.

If I run it again, start duplicating the lines, and what is not like, create the handler in another way, or use the existing one that would be appropriate.

$maxFiles = config('app.log_max_files');
$path     = storage_path('/logs/cprsync.log');

// Really I don't need this because this are on Laravel App, but with this method y can create a $handler for modify format 
$handler = new RotatingFileHandler($path, is_null($maxFiles) ? 5 : $maxFiles, config('app.log_level'));
(is_null(config('cprsync.activejob'))) ? $job = '' : $job=' ['.config('cprsync.activejob').']';
$logFormat = "[%datetime%] [%level_name%]".$job.": %message% %context% %extra%\n";

$formatter = new LineFormatter($logFormat,null,true,true);
$handler->setFormatter($formatter); // What I really want is to make this change ...

// Push handler
$log->getMonolog()->pushHandler($handler);

I don't know if it's the prettiest (like in Symfony you can just put some YAML rules in the services.yml and you've changed your log format), but this seems to be a very valid option and basically builds on what you're doing already:

http://laravel-tricks.com/tricks/monolog-for-custom-logging

TL;DR: Create a custom logging class with a function write() that basically contains the code OP has posted. Then add that class to your facades and you can log with MyCustomLogger::write($message);

EDIT: This isn't really what OP requested, since this doesn't change the format on runtime.

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