Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 629
Chris Avatar asked Mar 28 '15 01:03

Chris


1 Answers

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
like image 186
kba Avatar answered Sep 20 '22 18:09

kba