Symfony 2 : Log into a specific file

frinux picture frinux · Nov 23, 2011 · Viewed 13k times · Source

I searched a lot before posting my question. I didn't find a clear answer, so here it is.

I want to log messages in a different log file as dev.log or prod.log. I mean a file which won't be poluted by Symfony core messages. I heard about logger and handler in monolog, but it's not very clear.

How can I log messages from my controllers, model to a specific log file ?

Answer

Anda B picture Anda B · Feb 1, 2012

You have to add the info to the services.yml file, not the config.yml file:

So in services.yml (or services.xml) you have

my_service.logger:
    class:     Symfony\Bridge\Monolog\Logger
    arguments: [app]
    calls:
        - [pushHandler, [@my_service.logger_handler]]

my_service.logger_handler:
    class:     Monolog\Handler\StreamHandler       
    arguments: [%kernel.logs_dir%/%kernel.environment%.admin.log, 200]

and in your controller action you use:

$logger = $this->get('my_service.logger');