What isn't right with logging in Symfony 3

2.7k views Asked by At

I have configured logger for different channel in different files, but it does not work for me. It's work but it writes in console not in pointed file. And I need write log to file in channel search. Here is my code:

#app/config/config_dev.yml
monolog:
    handlers:
        search:
            type: stream
            level: error
            path: "%kernel.logs_dir%/search_log.log"
            channels: [search]
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug
            channels: [!event, !search]
        console:
            type:   console
            channels: [!event, !doctrine, !search]

Defined service:

#MyBundle/Resources/config/services.yml
services:
    app.logger_search:
            class: Symfony\Bridge\Monolog\Logger
            arguments: ["@logger"]
            tags:
                - {name: monolog.logger, channel: search}

Now use it service, try to test it:

#MyController.php

/**
 * @Route("/test")
 */
public function test()
{
    $this->get("app.logger_search")->error("Test");

    return $this->json("test");
}

But it writes into console insted of file. Console I meant where I ran my server: php bin\console server:run.

1

There are 1 answers

4
yceruto On BEST ANSWER

Creating your own Channel. This is done either via the configuration or by tagging your service with monolog.logger and specifying which channel the service should log to (just as you have done).

Both ways are valid and in both cases you logger will be named:

monolog.logger.<you-channel-name>

So use monolog.logger.search instead of your service id app.logger_search to fix the issue.

I you don't have a strong reason to change the logger behavior, I suggest to configure additional channels without tagged services:

# app/config/config.yml
monolog:
    channels: ['foo', 'bar']

With this, you can now send log messages to the foo channel by using the automatically registered logger service monolog.logger.foo.