13

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 ?

Mohammed H
  • 6,880
  • 16
  • 81
  • 127
frinux
  • 2,052
  • 6
  • 26
  • 47
  • 3
    Possible duplicate: http://stackoverflow.com/questions/8169114/how-to-write-logs-from-one-service-into-separate-file – Steven Mercatante Nov 23 '11 at 14:16
  • 1
    This iss kink of a duplicate, because your link is just part of the solution. I tried to add this services in app/config/config.yml, but had no way to make it work. No log file created so far. – frinux Nov 24 '11 at 08:54

2 Answers2

24

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');
Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
Anda B
  • 947
  • 7
  • 9
  • 1
    Thanks for your answer but with NetBeans, I got an error using : [@my_service.logger_handler] in order to make it work I had to add quotes : ["@my_service.logger_handler"] Hope it will help. – Ashbay Nov 08 '13 at 15:16
  • for me it only worked after I added it under services:, not directly in the yml file – Andreas May 31 '16 at 20:31
  • This answer should be set as the best one. Be careful about the quotes – Jul6art May 28 '19 at 16:55
2

The answer above worked perfectly fine for me. I had to adapt it though as my configuration was in xml and not yaml.

Here is the exact same configuration but using xml.

<service id="my_service.logger" class="Symfony\Bridge\Monolog\Logger">
    <argument type="string">app</argument>
    <call method="pushHandler">
        <argument type="service" id="my_service.logger_handler" />
    </call>
</service>
<service id="my_service.logger_handler" class="Monolog\Handler\StreamHandler">
    <argument>type="string">%kernel.logs_dir%/%kernel.environment%.license.log</argument>
    <argument type="string">200</argument>
</service>
jc.
  • 61
  • 5