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

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

 

Insert the logger in your service with a new Channel

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

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

The channel describes a new stack for logs.this

 

#Obtao/UserBundle/Resources/services.yml
wsse.security.authentication.listener:
    class:  Obtao\UserBundle\Security\Firewall\WsseListener
    arguments: ["@logger"]
    tags:
      - { name: monolog.logger, channel: wsse }

 

 

//Obtao\UserBundle\Security\Firewall\WsseListener.php
    protected $logger;

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

 

Your new channel is created.spa

Log something using your new Monolog channel 

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

 

//Obtao\UserBundle\Security\Firewall\WsseListener.php
$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)debug

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

 

[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. htm

Simply again, in the config/config_prod.yml fileget

 

#app/config/config_prod.yml
monolog:
    handlers:
        main:
            type          : fingers_crossed
            action_level  : error
            handler       : nested
            channels      : [!wsse]
            
        wsse:
            type: stream
            path: %kernel.logs_dir%/%kernel.environment%.wsse.log
            level: error
            channels: [wsse]
            
        nested:
            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.

相關文章
相關標籤/搜索