Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monolog Logger outputs empty arrays at the end of each log message

Tags:

php

monolog

My logger object is outputting empty arrays at the end of each line - [] []. For example;

[2017-08-17 12:26:02] import_log.INFO: checkForDuplicates::is_processing [] []
[2017-08-17 12:26:04] import_log.INFO: is duplicate [] []

Is there anyway I can stop this from occurring? I just want to log out without the empty arrays, ie, like the following:

[2017-08-17 12:26:02] import_log.INFO: checkForDuplicates::is_processing
[2017-08-17 12:26:04] import_log.INFO: is duplicate

I am creating my own logs like so:

protected function importXML($fName) {

    // Create a log file for each XML file imported
    $logger = new Logger("import_log");
    $logger->pushHandler(new StreamHandler(storage_path('./logs/' . $fName . '.log')), Logger::INFO);

    ....

    $logger->info($myString);


    ....

    $logger->info($myObject);
}
like image 764
sazr Avatar asked Dec 11 '22 10:12

sazr


1 Answers

These empty arrays are the context and extra attributes of your log entry. Context is provided as an additional array parameter when you add a log entry. Extra is populated by "processors" that you attach to your logger.

These empty arrays can be hidden:

When you don't define a formatter for Monolog, it will use a default LineFormatter. One of the constructor parameters for a LineFormatter is the option you're looking for:

public function __construct(string $format = null, string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false)

Specifically the 4th option is relevant - bool $ignoreEmptyContextAndExtra = false. If you create your own formatter:

$formatter = new LineFormatter(null, null, false, true);

Give it to your handler:

$handler = new StreamHandler(storage_path('./logs/' . $fName . '.log'));
$handler->setFormatter($formatter);

That should prevent the logger from showing empty arrays for "context" and "extra".

like image 175
Scopey Avatar answered May 02 '23 16:05

Scopey