Create new log file/channel for a Symfony Service with Monolog

Share Button

In this article about WSSE and Rest, we describe how to create a new log file/channel with monolog in Symfony2

Insert the logger in your service with a new Channel

In this example, our service is the wsse listener.(Reduced for the example) 

We add an argument : @logger which is defined as monolog.logger with the channel wsse

The channel describes a new stack for logs.

    class:  Obtao\UserBundle\Security\Firewall\WsseListener
    arguments: ["@logger"]
      - { name: monolog.logger, channel: wsse }

    protected $logger;

    public function __construct(LoggerInterface $logger)
        $this->logger = $logger;

Your new channel is created.

Log something using your new Monolog channel 

Very simple, in your service you just have to write:

$this->logger->err("WSSE Login failed for ".$username);

Here we log an error, we can log a warn or an info message (see : Symfony2 cookbook about monolog)

In logs files (prod.log or dev.log) you will see as an example : 

[2013-05-29 15:48:06] wsse.ERROR: WSSE Login failed for Obtao

Split files based on channel name

Now we need to split log files. 

Simply again, in the config/config_prod.yml file

            type          : fingers_crossed
            action_level  : error
            handler       : nested
            channels      : [!wsse]
            type: stream
            path: %kernel.logs_dir%/%kernel.environment%.wsse.log
            level: error
            channels: [wsse]
            type:  stream
            path:  %kernel.logs_dir%/%kernel.environment%.log
            level: debug

After your next error you will see a new file in your log dir : app/logs/prod.wsse.log

You can tell to your main logger not to handle wsse channel :

channels : [!wsse]

At the opposite [wsse] tells to your wsse logger to handle only wsse channel.

Read for further informations : 

Share Button

Comments are closed.