Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2: Injecting logger for specific channel/handler to services

I am working on a Symfony 2 web app and I would like to inject a Monolog logger using a specific channel to a service:

The Config:

monolog:
    handlers:
        main:
            type: stream
            path: %kernel.root_dir%/%kernel.environment%.log
            level: error
            #channels: [!alert]
        alert:
            type: stream
            path: %kernel.root_dir%/%kernel.environment%.alert.log
            level: info
            channels: [alert]

Service Config:

services:
    some_service:
     class: Some\Service
     arguments: [@logger]
     tags:
         - { name: monolog.logger, channel: alert }    

The Service:

class SomeService {
    protected $logger;

    public function __construct($logger) {  
        $this->logger = $logger;
        $this->logger->info('Log this!');
    }

The prod.log file:

[2016-03-28 11:25:47] alert.INFO: Log this!

The Problem: Although I specifically inject the logger using the alert channel, the message is handled by the main handler. Thus the messages are logged into the prod.log file instead of the prod.alert.log file.

When I leave the line channels: [!alert] as comment, the message is logged to prod.log. When I activate this line by removing the comment, the message is not logged at all (main handler ignores the channel correctly).

What have I to to, in order to use a specific handler to target a specific log file, mailer, etc? Messages to alert channel should be handled by the alert handler while all other handlers are ignored.

like image 969
Andrei Herford Avatar asked Mar 28 '16 11:03

Andrei Herford


1 Answers

Use special service created for Monolog handler:

services:
    some_service:
        class: Namespace\Some\Service
        arguments: ["@monolog.logger.alert"]
like image 185
Paweł Mikołajczuk Avatar answered Nov 12 '22 16:11

Paweł Mikołajczuk