Chr*_* W. 93 python django logging
我似乎无法弄清楚如何为我的Django安装设置"默认"记录器.我想使用Django 1.3的新LOGGING设置settings.py.
我查看了Django Logging Doc的示例,但它看起来像他们只设置处理程序,它将为特定记录器进行日志记录.在他们的示例中,他们为名为'django','django.request'和'myproject.custom'的记录器设置处理程序.
我想要做的就是设置一个默认值logging.handlers.RotatingFileHandler,默认情况下会处理所有记录器.也就是说,如果我在我的项目中的某个地方创建一个新模块,并且它被表示为:my_app_name.my_new_module,我应该能够做到这一点并让所有日志记录转到旋转文件日志.
# In file './my_app_name/my_new_module.py'
import logging
logger = logging.getLogger('my_app_name.my_new_module')
logger.debug('Hello logs!') # <-- This should get logged to my RotatingFileHandler that I setup in `settings.py`!
Run Code Online (Sandbox Code Playgroud)
Chr*_* W. 148
弄清楚了...
您可以通过使用空字符串引用它来设置'catch all'记录器:''.
例如,在以下设置中,我将保存所有日志事件,但将保存到logs/mylog.log的django.request日志事件除外logs/django_request.log.因为'propagate'设置False为我的django.request记录器,所以日志事件永远不会到达'catch all'记录器.
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'default': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': 'logs/mylog.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
'request_handler': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': 'logs/django_request.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': 'DEBUG',
'propagate': True
},
'django.request': {
'handlers': ['request_handler'],
'level': 'DEBUG',
'propagate': False
},
}
}
Run Code Online (Sandbox Code Playgroud)
Don*_*kby 22
正如您在答案中所说,Chris,定义默认记录器的一个选项是使用空字符串作为其键.
但是,我认为预期的方法是root在日志配置字典的键下定义一个特殊的记录器.我在Python文档中发现了这个:
root - 这将是根记录器的配置.配置的处理将与任何记录器一样,但该
propagate设置将不适用.
这是您的答案更改为使用root密钥的配置:
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'default': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': 'logs/mylog.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
'request_handler': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': 'logs/django_request.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
},
'root': {
'handlers': ['default'],
'level': 'DEBUG'
},
'loggers': {
'django.request': {
'handlers': ['request_handler'],
'level': 'DEBUG',
'propagate': False
},
}
}
Run Code Online (Sandbox Code Playgroud)
公平地说,我看不出两种配置之间的行为有什么不同.看来,使用空字符串键定义记录器将修改根记录器,因为logging.getLogger('')它将返回根记录器.
我比较喜欢的唯一原因'root'在''在于它是明确有关修改根记录.如果你很好奇,如果你定义了两个,则'root'覆盖'',只是因为最后处理了根条目.
| 归档时间: |
|
| 查看次数: |
46406 次 |
| 最近记录: |