Custom monolog handler for default monolog in Symfony 2

喜夏-厌秋 提交于 2019-11-29 05:56:24

问题


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?


回答1:


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.




回答2:


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%


来源:https://stackoverflow.com/questions/12935979/custom-monolog-handler-for-default-monolog-in-symfony-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!