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

2024-09-28 22:39:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用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的方法。你知道吗


Tags: djangodebugimportlog处理程序logginghandlers语法
3条回答

我认为应该添加一个新的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',
    },

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

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

感谢@jspcal,我找到了答案。定义如下处理程序工厂:

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

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

...

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

相关问题 更多 >