How to log multiline entries with monolog like a formatted array? How to log multiline entries with monolog like a formatted array? laravel laravel

How to log multiline entries with monolog like a formatted array?


Monolog uses Monolog\Formatter\LineFormatter by default without any arguments. Formatter is basically object that is responsible for final output in your logs. Look at constructor definition:

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

As you can see LineFormatter creates one line from your print_r output because of third argument. You need to define new service with custom arguments for LineFormatter.

# app/config/services.yml - for exampleservices:    monolog.my_line_formatter: # Your name        class: Monolog\Formatter\LineFormatter        arguments: [~, ~, true]

Now find your monolog definition and use formatter for what you need.

# Example from default config_dev.ymlmonolog:    handlers:        main:            type:   stream            path:   "%kernel.logs_dir%/%kernel.environment%.log"            level:  debug            formatter: monolog.my_line_formatter


You will need to use use Monolog\Formatter\LineFormatter to overwrite default settings for the log message formatter. Below is code:

use Monolog\Logger;use Monolog\Handler\StreamHandler;use Monolog\Formatter\LineFormatter;$logFilePath = __DIR__.'/path/to/logFile.log';$arr = array('abc' => 'xyz', 'qwerty' => 'yuiop', 'username' => 'abc xyz');$logger = new Logger('my_logger');$formatter = new LineFormatter(    null, // Format of message in log, default [%datetime%] %channel%.%level_name%: %message% %context% %extra%\n    null, // Datetime format    true, // allowInlineLineBreaks option, default false    true  // discard empty Square brackets in the end, default false);// Debug level handler$debugHandler = new StreamHandler($logFilePath, Logger::DEBUG);$debugHandler->setFormatter($formatter);$logger->pushHandler($debugHandler);$logger->info('FORMATTED ARRAY WITH MULTI-LINE');$logger->info(print_r($arr, true));

Below is the Log message written to the log file:

[2019-06-06 09:24:05] my_logger.INFO: FORMATTED ARRAY WITH MULTI-LINE  [2019-06-06 09:24:05] my_logger.INFO: Array(    [abc] => xyz    [qwerty] => yuiop    [username] => abc xyz)