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:
services: special_logger: class: Symfony\Bridge\Monolog\Logger arguments: [special] calls: - [pushHandler, [@special_handler]] special_handler: class: Monolog\Handler\StreamHandler arguments: [%kernel.logs_dir%/%kernel.environment%.special.log]
And to use it, inside any ContainerAware class
$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!