Symfony 2.1 - Switch Monolog channel in controller

Johannes Klauß picture Johannes Klauß · Apr 12, 2013 · Viewed 9.1k times · Source

I want to log into a different file than the usual dev.log or prod.log

I know that this can be done with different channels and I used it in several services, but I'm not very clear about switching the Monolog channel in a controller.

In a service you just define the channel via the tags attribute in the service definition, but how can I do this in a controller or even better in a specific action?

I know that a possible solution would be this: Symfony 2 : Log into a specific file

But it seems overkill to define two new services just for logging to a custom file.

Answer

Seldaek picture Seldaek · Apr 12, 2013

The only way to do this is to define your controller as a service and inject a custom logger with a custom channel.

Since the channels are created automatically there is currently no other way, but it's an interesting request and you're not the first, so I created an issue on MonologBundle to allow the definition of channels at the bundle configuration level. That way you could just fetch the proper logger from the controller using $this->get('monolog.logger.mychannel') (which you can already do if the channel exists, but not if you want a custom channel for the controller that nothing else uses).

Update:

As of symfony/monolog-bundle 2.4.0 you can define additional channels as:

monolog:
    channels: ["foo", "bar"]

Then you can retrieve it as $this->get('monolog.logger.mychannel')