9

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);
}
aknosis
  • 3,602
  • 20
  • 33
sazr
  • 24,984
  • 66
  • 194
  • 362
  • Does this answer your question? [How not to show last bracket in a monolog log line?](https://stackoverflow.com/questions/13968967/how-not-to-show-last-bracket-in-a-monolog-log-line) – Fabien Snauwaert Apr 08 '20 at 16:18

1 Answers1

18

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".

Scopey
  • 6,269
  • 1
  • 22
  • 34
  • Adding to this wonderful answer, to use LineFormatter, you'll need to `use \Monolog\Formatter\LineFormatter;` – clone45 Aug 20 '19 at 17:14
  • A more readable option (Monolog v2) would be `$formatter->ignoreEmptyContextAndExtra();`, right after the `LineFormatter` instance. – Binar Web Jun 06 '22 at 12:04
  • Starting with PHP 8, you can also use named arguments: `new LineFormatter(ignoreEmptyContextAndExtra : true)` – parttimeturtle Mar 07 '23 at 21:39