How to log messages to different files with Monolog in Symfony2.0

If you are logging lots of activity in your Symfony2.0 application you might have seen that it is not that obvious to split them into different files.

This has been solved in Symfony2.1, thanks to MonologBundle channels (Cookbook here) but if you are in Symfony2.0 and need to handle different log files this is the way to do so:

You’ll have to define a new Logger service and a Handler service for that logger. And this can be done in any of your configuration files under the services key like this:

1services:
2    special_logger:
3        class: Symfony\Bridge\Monolog\Logger
4        arguments: [special]
5        calls:
6            - [pushHandler, [@special_handler]]
7    special_handler:
8        class: Monolog\Handler\StreamHandler
9        arguments: [%kernel.logs_dir%/%kernel.environment%.special.log]

And to use it, inside any ContainerAware class

1$this->container->get('special_logger')->info('your message here');

And of course you can inject this new logger service into any of your application services and use it exactly the same way!

And that’s it, a new app/logs/prod.special.log (if you are using default settings) will be created and your special logs will end there!

Hope you liked this small trick!