Search code examples
symfonyautowiredmonologsymfony4

How to change Monolog channel for some controllers Symfony 3.4 or 4+


I want to change Monolog channel. My declarations works with some classes but never with controllers.

Here is my new admin channel declaration:

#config/packages/dev/monolog.yaml
monolog:
    handlers:
        admin:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%-admin.log"
            level: debug
            channels: ["admin"]

I use it successfuly with my Authenticator by adding a tag:

#config/services.yaml
# The form guard authenticator for the admin access
app.security.admin_authenticator:
    class: App\Security\AdminAuthenticator
    autowire: true
    tags:
        - { name: monolog.logger, channel: admin}

The last line of services.yaml file do the job, my Authenticator is no more logging in app channel, it's logging in admin channel.

Now, I want to use this channel with the controllers under the Admin subdirectory, so I add a similar tag in my declaration:

#config/services.yaml
App\Controller\Admin\:
    resource: '../src/Controller/Admin'
    tags:
        - 'controller.service_arguments'
        - { name: monolog.logger, channel: admin}

But it seems there is no impact. I am still logging in app channel. (I did some verification, like refresh the cache). I don't find my error.


Solution

  • I haven't tried this but it most probably because your controller doesn't implement LoggerAwareInterface thus the logger tag has no impact.

    Check which interface AdminAuthenticator is implementing (to see how the logger is being set) then do the same for the controller it should work.

    #services.yaml
    App\Controller\Admin\:
        resource: '../src/Controller/Admin'
        calls:
            - [ setLogger, [ '@logger' ] ]
        tags:
            - 'controller.service_arguments'
            - { name: monolog.logger, channel: admin}