如何使用dictConfig语法指定带有必需参数的日志处理程序类?

时间:2019-02-07 02:53:51

标签: python django logging

我想在Django中使用Notifiers日志记录处理程序。我的记录器使用dictConfig语法指定。

以下是Notifer自己的文档中的一个示例:

>>> import logging
>>> from notifiers.logging import NotificationHandler

>>> log = logging.getLogger(__name__)
>>> defaults = {
...    'token': 'foo,
...    'user': 'bar
... }

>>> hdlr = NotificationHandler('pushover', defaults=defaults)
>>> hdlr.setLevel(logging.ERROR)

>>> log.addHandler(hdlr)
>>> log.error('And just like that, you get notified about all your errors!')

dictConfig语法如下:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/django/debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

如何使用后一种语法添加通告程序处理程序?我找不到将第一个必需参数设置为NotificationHandler的方法。

3 个答案:

答案 0 :(得分:1)

也许指定您自己的工厂类以实例化处理程序。可以使用此处描述的()语法完成:

https://docs.python.org/3/library/logging.config.html#logging-config-dict-userdef

答案 1 :(得分:1)

由于@jspcal,我找到了答案。定义这样的处理程序工厂:

def slack_handler_factory():
    return NotificationHandler(
        'slack',
        defaults={
            'webhook_url': SLACK_WEBHOOK_URL,
        },
    )

..并且可以使用()语法将其添加到处理程序中:

...

'handlers': {
    'slack': {
        '()': slack_handler_factory,
        'level': 'WARNING',
    },
...

答案 2 :(得分:0)

我认为应该通过添加新的handler来起作用:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/django/debug.log',
        },
        'notify': {
            'level': 'DEBUG',
            'class': 'notifiers.logging.NotificationHandler',
        },
    },
    'loggers': {
        'django': {  # or you can add any new logger if you want
            'handlers': ['notify'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

更新

可以通过覆盖NotificationHandler来解决此问题:

class CustomNotificationHandler(NotificationHandler):
     def __init__(self, *args, **kwargs):
         defaults = {
           'token': 'foo,
           'user': 'bar
         }
         super(CustomNotificationHandler, self).__init__('pushover', defaults)

并在Django日志中的处理程序中使用它。

'notify': {
        'level': 'DEBUG',
        'class': 'CustomNotificationHandler',
    },