How to write and use Monolog handlers and channels

4.6k views Asked by At

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?

1

There are 1 answers

0
Ugur On BEST ANSWER

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