Search code examples
phpsymfonymonologsymfony-2.6

How to write and use Monolog handlers and channels


I have read some docs here but still not clear to me how to write and use a custom Monolog handler and channel. Let me explain a bit what I want to achieve. I have a custom function and I want that log to be logged into a file called custom.log. I have enabled Doctrine logging into another file by setting this in config.yml file:

monolog:
    handlers:
        #Logs Doctrine to a different channel
        doctrine:
            level:    debug
            type:     stream
            path:     "%kernel.logs_dir%/doctrine.log"
            channels: [doctrine]

How do I achieve the same for a custom.log?


Solution

  • You can try that way,

    monolog:
        channels: ["testchannel"]
        handlers:
            test:
                # log all messages (since debug is the lowest level)
                level:    debug
                type:     stream
                path:     "%kernel.logs_dir%/testchannel.log"
                channels: ["testchannel"]
    

    And in the controller you can get the logger and do your thing;

    class DefaultController extends Controller
    {
        public function indexAction()
        {
    
           $logger = $this->get('monolog.logger.testchannel');
           $logger->info("This one goes to test channel!!");
           return $this->render('AcmeBundle:Default:index.html.twig');
        }
    }
    

    Also you can check which monolog handlers and loggers are registered by running the command php app/console container:debug monolog