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

前端 未结 2 746
悲&欢浪女
悲&欢浪女 2021-02-19 08:08

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

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


        
2条回答
  •  天命终不由人
    2021-02-19 08:46

    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
    )
    

提交回复
热议问题