Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by
  1. Home
  2. Documentation
  3. Logging
  4. How to Log Messages to different Files

How to Log Messages to different Files

Edit this page

The Symfony Framework organizes log messages into channels. By default, there are several channels, including doctrine, event, security, request and more. The channel is printed in the log message and can also be used to direct different channels to different places/files.

By default, Symfony logs every message into a single file (regardless of the channel).

Note

Each channel corresponds to a different logger service (monolog.logger.XXX) Use the php bin/console debug:container monolog command to see a full list of services and learn how to autowire monolog channels.

Switching a Channel to a different Handler

Now, suppose you want to log the security channel to a different file. To do this, create a new handler and configure it to log only messages from the security channel. The following example does that only in the prod configuration environment:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# config/packages/monolog.yaml
when@prod:
    monolog:
        handlers:
            security:
                # log all messages (since debug is the lowest level)
                level:    debug
                type:     stream
                path:     '%kernel.logs_dir%/security.log'
                channels: [security]

            # an example of *not* logging security channel messages for this handler
            main:
                # ...
                # channels: ['!security']
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
<!-- config/packages/prod/monolog.xml-->
<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
        https://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/monolog
        https://symfony.com/schema/dic/monolog/monolog-1.0.xsd">

    <when env="prod">
        <monolog:config>
            <monolog:handler name="security" type="stream" path="%kernel.logs_dir%/security.log">
                <monolog:channels>
                    <monolog:channel>security</monolog:channel>
                </monolog:channels>
            </monolog:handler>
        </monolog:config>
    </when>

        <monolog:handler name="main" type="stream" path="%kernel.logs_dir%/main.log">
            <!-- ... -->
            <monolog:channels>
                <monolog:channel>!security</monolog:channel>
            </monolog:channels>
        </monolog:handler>
    </monolog:config>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// config/packages/prod/monolog.php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Config\MonologConfig;

return static function (MonologConfig $monolog, ContainerConfigurator $container) {
    if ('prod' === $container->env()) {
        $monolog->handler('security')
            ->type('stream')
            ->path(param('kernel.logs_dir') . \DIRECTORY_SEPARATOR . 'security.log')
            ->channels()->elements(['security']);

        $monolog->handler('main')
             // ...

            ->channels()->elements(['!security']);
    }
};

Caution

The channels configuration only works for top-level handlers. Handlers that are nested inside a group, buffer, filter, fingers crossed or other such handler will ignore this configuration and will process every message passed to them.

You can specify the configuration in different ways:

1
2
3
4
5
6
7
channels: ~    # Include all the channels

channels: foo  # Include only channel 'foo'
channels: '!foo' # Include all channels, except 'foo'

channels: [foo, bar]   # Include only channels 'foo' and 'bar'
channels: ['!foo', '!bar'] # Include all channels, except 'foo' and 'bar'

Creating your own Channel

You can change the channel Monolog logs to one service at a time. This is done either via the configuration below or by tagging your service with monolog.logger and specifying which channel the service should log to. With the tag, the logger that is injected into that service is preconfigured to use the channel you've specified.

Configure Additional Channels without Tagged Services

You can also configure additional channels without the need to tag your services:

1
2
3
# config/packages/monolog.yaml
monolog:
    channels: ['foo', 'bar', 'foo_bar']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- config/packages/monolog.xml -->
<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
        https://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/monolog
        https://symfony.com/schema/dic/monolog/monolog-1.0.xsd">

    <monolog:config>
        <monolog:channel>foo</monolog:channel>
        <monolog:channel>bar</monolog:channel>
        <monolog:channel>foo_bar</monolog:channel>
    </monolog:config>
</container>
1
2
3
4
5
6
// config/packages/monolog.php
use Symfony\Config\MonologConfig;

return static function (MonologConfig $monolog): void {
    $monolog->channels(['foo', 'bar', 'foo_bar']);
};

Symfony automatically registers one service per channel (in this example, the channel foo creates a service called monolog.logger.foo). In order to inject this service into others, you must update the service configuration to choose the specific service to inject.

How to Autowire Logger Channels

Starting from MonologBundle 3.5 you can autowire different Monolog channels by type-hinting your service arguments with the following syntax: Psr\Log\LoggerInterface $<camelCased channel name> + Logger. The <channel> must have been predefined in your Monolog configuration.

For example to inject the service related to the foo_bar logger channel, change your constructor like this:

1
2
3
4
5
public function __construct(
-     LoggerInterface $logger,
+     LoggerInterface $fooBarLogger,
    ) {
    }

Configure Logger Channels with Attributes

Starting from Monolog 3.5 you can also configure the logger channel by using the #[WithMonologChannel] attribute directly on your service class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/Service/MyFixtureService.php
namespace App\Service;

use Monolog\Attribute\WithMonologChannel;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Monolog\Logger;

#[WithMonologChannel('fixtures')]
class MyFixtureService
{
    public function __construct(LoggerInterface $logger)
    {
        // ...
    }
}

This way you can avoid declaring your service manually to use a specific channel.

3.5

The #[WithMonologChannel] attribute was introduced in Monolog 3.5.0.

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

    Symfony 7.1 is backed by

    Take the exam at home

    Take the exam at home

    Save your teams and projects before they sink

    Save your teams and projects before they sink

    Version:

    Table of Contents

    • Switching a Channel to a different Handler
    • Creating your own Channel
      • Configure Additional Channels without Tagged Services
      • How to Autowire Logger Channels
      • Configure Logger Channels with Attributes

    Symfony footer

    Avatar of inspiran, a Symfony contributor

    Thanks inspiran for being a Symfony contributor

    1 commit • 71 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?

      • What is Symfony?
      • Symfony at a Glance
      • Symfony Components
      • 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

      • Symfony Community
      • SymfonyConnect
      • Events & Meetups
      • Projects using Symfony
      • Contributors
      • Symfony Jobs
      • Backers
      • Code of Conduct
      • Downloads Stats
      • Support
    • Blog

      • All Blog Posts
      • A Week of Symfony
      • Case Studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Living on the edge
      • Releases
      • Security Advisories
      • Symfony Insight
      • Twig
      • SensioLabs Blog
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Powered by

    Follow Symfony