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

China☆狼群 提交于 2019-12-21 07:49:23

问题


I am trying to log an array with monolog in symfony.

$logger = $this->get('logger');
$logger->info(=print_R($user,true));

the output i get is not formatted as a print_r would be expected. It logs it all on one line.

I do not have any monolog settings in my config.yml and suspect this may be the issue.

How can I log a print_r(array) using monolog so it displays formatted in a tail -f?


回答1:


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 example
services:
    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.yml
monolog:
    handlers:
        main:
            type:   stream
            path:   "%kernel.logs_dir%/%kernel.environment%.log"
            level:  debug
            formatter: monolog.my_line_formatter



回答2:


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
)


来源:https://stackoverflow.com/questions/29312746/how-to-log-multiline-entries-with-monolog-like-a-formatted-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!