1
votes

I have started learning Symfony2 and currently I am dealing with a command that I want to log separately.

My goal is to use a custom logger and get a clean log file for my command. I work on a project that uses xml configuration files but I don't get how to translate some .yml parameters and options.

I have read How to write logs from one service into separate file? and got a working separate log file.

<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="myproject_mycommand.logger" class="Symfony\Bridge\Monolog\Logger">
            <argument>myproject_mycommand.logger</argument>
            <call method="pushHandler">
                <argument type="service" id="myproject_mycommand.logger_handler" />
            </call>
        </service>

        <service id="myproject_mycommand.logger_handler" class="Monolog\Handler\StreamHandler">
            <argument>%kernel.logs_dir%/my_custom_file_log.log</argument>
        </service>
    </services>
</container>

After looking Symfony2 : use Processors while logging in different files I'm trying to pass only my desired fields to the monolog line formatter, something like "[%%datetime%%] %%message%%\n"

I guess that I would have to add something like:

container
...
    xmlns:monolog="http://symfony.com/schema/dic/monolog"
... 

and

<service id="myproject_mycommand.logger.formatter" class="Monolog\Formatter\LineFormatter">
    <argument>"[%%datetime%%] %%message%%\n"</argument>
</service>

but I don't get how to configure this simple formatter in the xml file.

Thanks for your help!

1

1 Answers

1
votes

You need to create your formatter and extend it from FormatterInterface and implement format and formatBatch.

Then add service definition

<service id="myproject_mycommand.logger.formatter" class="MyBundle\Formatter\XmlFormatter">
    <argument>some arguments if you need one</argument>
</service>

<service id="myproject_mycommand.logger_handler" class="Monolog\Handler\StreamHandler">
    <argument>%kernel.logs_dir%/my_custom_file_log.log</argument>
    <call method="setFormatter">
        <argument type="service" id="myproject_mycommand.logger.formatter"/>
    </call>    
</service>

That's about it. For idea of how to format you can check examples of different formatters inside monolog bundle sources.