How to add additional information (Host, URL, etc.) to Symfony/Monolog log output? How to add additional information (Host, URL, etc.) to Symfony/Monolog log output? symfony symfony

How to add additional information (Host, URL, etc.) to Symfony/Monolog log output?


If you want to add extra information to log entries, you can do this with a processor. With a processor you can modify the record array, before it's parsed by a formatter. The extra part is shown at the end of the log entry.

<?phpnamespace AppBundle\Monolog;use Symfony\Component\HttpFoundation\RequestStack;class WebProcessor{    private $requestStack;    public function __construct(RequestStack $requestStack)    {        $this->requestStack = $requestStack;    }    public function processRecord(array $record)    {        $request = $this->requestStack->getCurrentRequest();        if ($request) {            $record['extra']['host'] = $request->getHost();            $record['extra']['url'] = $request->getRequestUri();            // ...        }        return $record;    }}

Now add it to your services.yml to register it for all log entries:

app.monolog.processor.web:    class: AppBundle\Monolog\WebProcessor    arguments: ["@request_stack"]    tags:        - { name: monolog.processor, method: processRecord }


Don't reinvent the wheel! There is no need to write your own WebProcessor, since Monolog already has it.

The only thing you have to do is add it to your services and tag it with monolog.processor:

# app/config/services.ymlservices:    Monolog\Processor\WebProcessor:        tags: ['monolog.processor']

Monolog has even more built-in processors you can use. I decided to add multiple processors in my application:

# app/config/services/monolog.yml (I included services/*.yml in config.yml)services:    _defaults:        tags: ['monolog.processor']    Monolog\Processor\WebProcessor: ~    Monolog\Processor\GitProcessor: ~    Monolog\Processor\MemoryUsageProcessor: ~    Monolog\Processor\MemoryPeakUsageProcessor: ~    Monolog\Processor\IntrospectionProcessor: ~


You can use a custom formatter to change the output written to the monolog log files. You can find more information about this subject here: http://symfony.com/doc/current/cookbook/logging/monolog.html#changing-the-formatter

Short version: you can create a custom formatter class that implements Monolog\Formatter\FormatterInterface and you can enable it in your config.yml file this way:

# app/config/config.ymlservices:    my_formatter:        class: Monolog\Formatter\JsonFormattermonolog:    handlers:        file:            type: stream            level: debug            formatter: my_formatter