如何像格式化数组一样使用独白记录多行条目?

问题描述 投票:0回答:3

我正在尝试用

monolog
记录一个数组
symfony

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

我得到的输出未格式化为 print_r 预期的格式。它将所有内容记录在一行中。

我的

config.yml
中没有任何独白设置,怀疑这可能是问题所在。

如何使用独白记录

print_r(array)
,使其以
tail -f
格式显示?

laravel symfony logging monolog
3个回答
21
投票

Monolog 默认使用

Monolog\Formatter\LineFormatter
,不带任何参数。格式化程序基本上是负责日志中最终输出的对象。查看构造函数定义:

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

如您所见,由于第三个参数,LineFormatter 从 print_r 输出中创建一行。您需要使用

LineFormatter
的自定义参数定义新服务。

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

现在找到您的独白定义并使用格式化程序来满足您的需要。

# 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

7
投票

您将需要使用

use Monolog\Formatter\LineFormatter
覆盖日志消息格式化程序的默认设置。下面是代码:

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));

以下是写入日志文件的日志消息:

[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
)

0
投票

在通道['single']的'config/logging.php'中定义如下内容:

use Monolog\Formatter\LineFormatter;

...

        'single' => [
            'driver' => 'single',
            'formatter' => LineFormatter::class,
            'formatter_with' => [
                'format' => "[%datetime%] %channel%.%level_name%: %message%\n %context%\n",
                'dateFormat' => "Y-m-d H:i:s",
                'allowInlineLineBreaks' => true
            ],
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
        ],

请注意这个附加参数

allowInlineLineBreaks
设置为 true。

© www.soinside.com 2019 - 2024. All rights reserved.