rob*_*rob 7 django exception-handling exception django-logging django-1.11
我正在尝试创建一个基于类的日志记录处理程序,当应用程序使用django提供的一些内置日志记录配置查看DisallowedHost异常时,它会通知某些第三方服务.
但是,我收到一个特殊的import错误,我无法理解如何解决.
我的settings.py
LOGGING = {
...
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'notify_my_service': {
'level': 'ERROR',
'class': 'tools.exception_logging.NotifyMyServiceHandler'
}
},
'loggers': {
...
'django.security.DisallowedHost': {
'handlers': ['notify_my_service'],
'propagate': False,
},
},
}
Run Code Online (Sandbox Code Playgroud)
我的异常处理程序
import logging
class NotifyMyServiceHandler(logging.handlers.HTTPHandler):
def emit(self, error):
doSomething()
Run Code Online (Sandbox Code Playgroud)
大回溯
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 250, in raise_last_exception
six.reraise(*_exception)
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/usr/local/lib/python2.7/dist-packages/django/utils/log.py", line 75, in configure_logging
logging_config_func(logging_settings)
File "/usr/lib/python2.7/logging/config.py", line 794, in dictConfig
dictConfigClass(config).configure()
File "/usr/lib/python2.7/logging/config.py", line 576, in configure
'%r: %s' % (name, e))
ValueError: Unable to configure handler 'notify_my_service': 'module' object has no attribute 'handlers'
Run Code Online (Sandbox Code Playgroud)
因此,由于某种原因,日志记录模块似乎未正确导入.我尝试过其他线程的示例,例如在异常处理程序模块中导入设置.
是否有可能以这种方式为django日志记录编写自定义处理程序?
当我在这里使用代码模拟你的情况时,我遇到的问题是这个代码,因为logging模块没有handlers属性而导致错误.
import logging
class NotifyMyServiceHandler(logging.handlers.HTTPHandler):
def emit(self, error):
doSomething()
Run Code Online (Sandbox Code Playgroud)
您要找的是导入logging.handlers模块.所以你需要:
import logging.handlers
class NotifyMyServiceHandler(logging.handlers.HTTPHandler):
def emit(self, error):
doSomething()
Run Code Online (Sandbox Code Playgroud)
不幸的是,logging.config模块通过引发隐藏原始堆栈跟踪的新异常来报告错误,这使得难以找到原始错误.