Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Logging
  4. How to Add extra Data to Log Messages via a Processor
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

Table of Contents

  • Adding a Session/Request Token
  • Registering Processors per Handler
  • Registering Processors per Channel

How to Add extra Data to Log Messages via a Processor

Edit this page

Warning: You are browsing the documentation for Symfony 2.7, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

How to Add extra Data to Log Messages via a Processor

Monolog allows you to process the record before logging it to add some extra data. A processor can be applied for the whole handler stack or only for a specific handler.

A processor is simply a callable receiving the record as its first argument. Processors are configured using the monolog.processor DIC tag. See the reference about it.

Adding a Session/Request Token

Sometimes it is hard to tell which entries in the log belong to which session and/or request. The following example will add a unique token for each request using a processor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
namespace AppBundle\Logger;

use Symfony\Component\HttpFoundation\Session\SessionInterface;

class SessionRequestProcessor
{
    private $session;
    private $sessionId;

    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    public function processRecord(array $record)
    {
        if (!$this->session->isStarted()) {
            return $record;
        }

        if (!$this->sessionId) {
            $this->sessionId = substr($this->session->getId(), 0, 8) ?: '????????';
        }

        $record['extra']['token'] = $this->sessionId.'-'.substr(uniqid('', true), -8);

        return $record;
    }
}
  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# app/config/config.yml
services:
    monolog.formatter.session_request:
        class: Monolog\Formatter\LineFormatter
        arguments:
            - "[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%% %%context%% %%extra%%\n"

    app.logger.session_request_processor:
        class: AppBundle\Logger\SessionRequestProcessor
        arguments:  ['@session']
        tags:
            - { name: monolog.processor, method: processRecord }

monolog:
    handlers:
        main:
            type: stream
            path: '%kernel.logs_dir%/%kernel.environment%.log'
            level: debug
            formatter: monolog.formatter.session_request
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!-- app/config/config.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:monolog="http://symfony.com/schema/dic/monolog"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/monolog
        http://symfony.com/schema/dic/monolog/monolog-1.0.xsd">

    <services>
        <service id="monolog.formatter.session_request"
            class="Monolog\Formatter\LineFormatter">

            <argument>[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%% %%context%% %%extra%%&#xA;</argument>
        </service>

        <service id="app.logger.session_request_processor"
            class="AppBundle\Logger\SessionRequestProcessor">

            <argument type="service" id="session" />
            <tag name="monolog.processor" method="processRecord" />
        </service>
    </services>

    <monolog:config>
        <monolog:handler
            name="main"
            type="stream"
            path="%kernel.logs_dir%/%kernel.environment%.log"
            level="debug"
            formatter="monolog.formatter.session_request"
        />
    </monolog:config>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// app/config/config.php
use AppBundle\Logger\SessionRequestProcessor;
use Monolog\Formatter\LineFormatter;

$container
    ->register('monolog.formatter.session_request', LineFormatter::class)
    ->addArgument('[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%% %%context%% %%extra%%\n');

$container
    ->register('app.logger.session_request_processor', SessionRequestProcessor::class)
    ->addArgument(new Reference('session'))
    ->addTag('monolog.processor', array('method' => 'processRecord'));

$container->loadFromExtension('monolog', array(
    'handlers' => array(
        'main' => array(
            'type'      => 'stream',
            'path'      => '%kernel.logs_dir%/%kernel.environment%.log',
            'level'     => 'debug',
            'formatter' => 'monolog.formatter.session_request',
        ),
    ),
));

Note

If you use several handlers, you can also register a processor at the handler level or at the channel level instead of registering it globally (see the following sections).

Registering Processors per Handler

You can register a processor per handler using the handler option of the monolog.processor tag:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
# app/config/config.yml
services:
    app.logger.session_request_processor:
        class: AppBundle\Logger\SessionRequestProcessor
        arguments:  ['@session']
        tags:
            - { name: monolog.processor, method: processRecord, handler: main }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- app/config/config.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:monolog="http://symfony.com/schema/dic/monolog"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/monolog
        http://symfony.com/schema/dic/monolog/monolog-1.0.xsd">

    <services>
        <service id="app.logger.session_request_processor
            class="AppBundle\Logger\SessionRequestProcessor">

            <argument type="service" id="session" />
            <tag name="monolog.processor" method="processRecord" handler="main" />
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
// app/config/config.php

// ...
$container
    ->register(
        'app.logger.session_request_processor',
        SessionRequestProcessor::class
    )
    ->addArgument(new Reference('session'))
    ->addTag('monolog.processor', array('method' => 'processRecord', 'handler' => 'main'));

Registering Processors per Channel

You can register a processor per channel using the channel option of the monolog.processor tag:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
# app/config/config.yml
services:
    app.logger.session_request_processor:
        class: AppBundle\Logger\SessionRequestProcessor
        arguments:  ['@session']
        tags:
            - { name: monolog.processor, method: processRecord, channel: main }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- app/config/config.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:monolog="http://symfony.com/schema/dic/monolog"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/monolog
        http://symfony.com/schema/dic/monolog/monolog-1.0.xsd">

    <services>
        <service id="app.logger.session_request_processor"
            class="AppBundle\Logger\SessionRequestProcessor">

            <argument type="service" id="session" />
            <tag name="monolog.processor" method="processRecord" channel="main" />
        </service>
    </services>
</container>
1
2
3
4
5
6
7
// app/config/config.php

// ...
$container
    ->register('app.logger.session_request_processor', SessionRequestProcessor::class)
    ->addArgument(new Reference('session'))
    ->addTag('monolog.processor', array('method' => 'processRecord', 'channel' => 'main'));
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:
Measure & Improve Symfony Code Performance

Measure & Improve Symfony Code Performance

Code consumes server resources. Blackfire tells you how

Code consumes server resources. Blackfire tells you how

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of Nicolás Alonso, a Symfony contributor

Thanks Nicolás Alonso for being a Symfony contributor

2 commits • 8 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia