How to Add extra Data to Log Messages via a Processor

How to Add extra Data to Log Messages via a Processor

Monolog allows you to process every record before logging it by adding some extra data. This is the role of a processor, which can be applied for the whole handler stack or only for a specific handler or channel.

A processor is 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. // src/Logger/SessionRequestProcessor.php
  2. namespace App\Logger;
  3. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  4. class SessionRequestProcessor
  5. {
  6. private $session;
  7. private $sessionId;
  8. public function __construct(SessionInterface $session)
  9. {
  10. $this->session = $session;
  11. }
  12. // this method is called for each log record; optimize it to not hurt performance
  13. public function __invoke(array $record)
  14. {
  15. if (!$this->session->isStarted()) {
  16. return $record;
  17. }
  18. if (!$this->sessionId) {
  19. $this->sessionId = substr($this->session->getId(), 0, 8) ?: '????????';
  20. }
  21. $record['extra']['token'] = $this->sessionId.'-'.substr(uniqid('', true), -8);
  22. return $record;
  23. }
  24. }

Next, register your class as a service, as well as a formatter that uses the extra information:

  • YAML

    1. # config/services.yaml
    2. services:
    3. monolog.formatter.session_request:
    4. class: Monolog\Formatter\LineFormatter
    5. arguments:
    6. - "[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%% %%context%% %%extra%%\n"
    7. App\Logger\SessionRequestProcessor:
    8. tags:
    9. - { name: monolog.processor }
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:monolog="http://symfony.com/schema/dic/monolog"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/monolog
    9. https://symfony.com/schema/dic/monolog/monolog-1.0.xsd">
    10. <services>
    11. <service id="monolog.formatter.session_request"
    12. class="Monolog\Formatter\LineFormatter">
    13. <argument>[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%% %%context%% %%extra%%&#xA;</argument>
    14. </service>
    15. <service id="App\Logger\SessionRequestProcessor">
    16. <tag name="monolog.processor"/>
    17. </service>
    18. </services>
    19. </container>
  • PHP

    1. // config/services.php
    2. use App\Logger\SessionRequestProcessor;
    3. use Monolog\Formatter\LineFormatter;
    4. $container
    5. ->register('monolog.formatter.session_request', LineFormatter::class)
    6. ->addArgument('[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%% %%context%% %%extra%%\n');
    7. $container
    8. ->register(SessionRequestProcessor::class)
    9. ->addTag('monolog.processor');

Finally, set the formatter to be used on whatever handler you want:

  • YAML

    1. # config/packages/prod/monolog.yaml
    2. monolog:
    3. handlers:
    4. main:
    5. type: stream
    6. path: '%kernel.logs_dir%/%kernel.environment%.log'
    7. level: debug
    8. formatter: monolog.formatter.session_request
  • XML

    1. <!-- config/packages/prod/monolog.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:monolog="http://symfony.com/schema/dic/monolog"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/monolog
    9. https://symfony.com/schema/dic/monolog/monolog-1.0.xsd">
    10. <monolog:config>
    11. <monolog:handler
    12. name="main"
    13. type="stream"
    14. path="%kernel.logs_dir%/%kernel.environment%.log"
    15. level="debug"
    16. formatter="monolog.formatter.session_request"
    17. />
    18. </monolog:config>
    19. </container>
  • PHP

    1. // config/packages/prod/monolog.php
    2. $container->loadFromExtension('monolog', [
    3. 'handlers' => [
    4. 'main' => [
    5. 'type' => 'stream',
    6. 'path' => '%kernel.logs_dir%/%kernel.environment%.log',
    7. 'level' => 'debug',
    8. 'formatter' => 'monolog.formatter.session_request',
    9. ],
    10. ],
    11. ]);

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

Symfony’s MonologBridge provides processors that can be registered inside your application.

Symfony\Bridge\Monolog\Processor\DebugProcessor

Adds additional information useful for debugging like a timestamp or an error message to the record.

Symfony\Bridge\Monolog\Processor\TokenProcessor

Adds information from the current user’s token to the record namely username, roles and whether the user is authenticated.

Symfony\Bridge\Monolog\Processor\WebProcessor

Overrides data from the request using the data inside Symfony’s request object.

Symfony\Bridge\Monolog\Processor\RouteProcessor

Adds information about current route (controller, action, route parameters).

Symfony\Bridge\Monolog\Processor\ConsoleCommandProcessor

Adds information about current console command.

New in version 4.3: The RouteProcessor and the ConsoleCommandProcessor were introduced in Symfony 4.3.

See also

Check out the built-in Monolog processors to learn more about how to create these processors.

Registering Processors per Handler

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

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\Logger\SessionRequestProcessor:
    4. tags:
    5. - { name: monolog.processor, handler: main }
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:monolog="http://symfony.com/schema/dic/monolog"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/monolog
    9. https://symfony.com/schema/dic/monolog/monolog-1.0.xsd">
    10. <services>
    11. <service id="App\Logger\SessionRequestProcessor">
    12. <tag name="monolog.processor" handler="main"/>
    13. </service>
    14. </services>
    15. </container>
  • PHP

    1. // config/services.php
    2. // ...
    3. $container
    4. ->register(SessionRequestProcessor::class)
    5. ->addTag('monolog.processor', ['handler' => 'main']);

Registering Processors per Channel

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

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\Logger\SessionRequestProcessor:
    4. tags:
    5. - { name: monolog.processor, channel: main }
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:monolog="http://symfony.com/schema/dic/monolog"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/monolog
    9. https://symfony.com/schema/dic/monolog/monolog-1.0.xsd">
    10. <services>
    11. <service id="App\Logger\SessionRequestProcessor">
    12. <tag name="monolog.processor" channel="main"/>
    13. </service>
    14. </services>
    15. </container>
  • PHP

    1. // config/services.php
    2. // ...
    3. $container
    4. ->register(SessionRequestProcessor::class)
    5. ->addTag('monolog.processor', ['channel' => 'main']);

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.