Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 : Log into a specific file

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 ?

like image 450
frinux Avatar asked Nov 23 '11 11:11

frinux


People also ask

How do I write logs in a separate file?

- Create a new appender by copying the FILE appender and change the name and path according to the requirement. - Add a threshold parameter to the new appender with the value set to the level to be logged. This will mean that all entries having this log level and above will be written into the file.

Where does Symfony write logs?

By default, log entries are written to the var/log/dev. log file when you're in the dev environment. In the prod environment, logs are written to STDERR PHP stream, which works best in modern containerized applications deployed to servers without disk write permissions.

What is monolog Symfony?

Monolog is the existing standard logging library for PHP. It is most popular in PHP frameworks such as Laravel and Symfony, where it implements a common interface for logging libraries. This article talks about the step-by-step process of using PHP Monolog in your application.


2 Answers

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');
like image 93
Anda B Avatar answered Oct 02 '22 06:10

Anda B


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>
like image 24
jc. Avatar answered Oct 02 '22 06:10

jc.