Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom monolog handler for default monolog in Symfony 2

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?

like image 646
TroodoN-Mike Avatar asked Oct 17 '12 13:10

TroodoN-Mike


2 Answers

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.

like image 84
chmeliuk Avatar answered Nov 08 '22 23:11

chmeliuk


I just found out that Monolog ships with a set of various handlers so you might wanna use one of those instead of writing your own. I am using the LogEntriesHandler for logging to logentries.com but there are a few more as documented here: https://github.com/Seldaek/monolog#log-specific-servers-and-networked-logging

My Symfony2 config for that looks like that:

monolog:
    main:
        type:  fingers_crossed
        level: debug
        handler: nested
    custom:
        type: service
        id: monolog.handler.logentries
        level: error

services:
    monolog.handler.logentries:
        class: Monolog\Handler\LogEntriesHandler
        arguments:
            token: %logentries_token%
like image 8
totas Avatar answered Nov 08 '22 23:11

totas