Custom monolog handler for default monolog in Symfony 2

TroodoN-Mike picture TroodoN-Mike · Oct 17, 2012 · Viewed 17.9k times · Source

I want to add a custom handler to a default monolog in Symfony 2.

In my config.yaml file, I have:

monolog:
    handlers:
        main:
            type:  stream
            path:  %kernel.logs_dir%/%kernel.environment%.log
            level: debug
        myHandler:
            type:  Acme\MyBundle\Monolog\MyCustomHandler
            level: error

My class looks like below:

// Acme\MyBundle\Monolog\MyCustomHandler
use Monolog\Logger;
use Monolog\Handler\SocketHandler;
use Monolog\Formatter\LineFormatter;

class MyCustomHandler extends AbstractProcessingHandler
{
    ...
}

But even before I fill my class in I get an error:

invalid handler type "acme\mybundle\monolog\mycustomhandler" given for handler "myHandler"

How do I add a custom handler to the default monolog without creating a new monolog service?

Answer

chmeliuk picture chmeliuk · Oct 17, 2012

Try this:

monolog:
    handlers:
        main:
            type:  stream
            path:  %kernel.logs_dir%/%kernel.environment%.log
            level: debug
        custom:
            type: service
            id: my_custom_handler

services:
    my_custom_handler:
        class: Acme\MyBundle\Monolog\MyCustomHandler

If you want to use it as default handler then you should change a bit monolog section I wrote above.

monolog:
    handlers:
        main:
            type:  stream
            path:  %kernel.logs_dir%/%kernel.environment%.log
            level: debug
            handler: custom
        custom:
            type: service
            id: my_custom_handler

I hope it helps you.