在 Python 日志记录中有两个不同的概念:记录器记录的级别和处理程序实际激活的级别。
当调用 log 时,基本上发生的是:
if self.level <= loglevel:
for handler in self.handlers:
handler(loglevel, message)
而这些处理程序中的每一个都将调用:
if self.level <= loglevel:
# do something spiffy with the log!
如果您想对此进行实际演示,可以查看Django 的配置设置。我将在此处包含相关代码。
LOGGING = {
#snip
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console':{
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['special']
}
},
'loggers': {
#snip
'myproject.custom': {
# notice how there are two handlers here!
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
'filters': ['special']
}
}
}
因此,在上面的配置中,只有到getLogger('myproject.custom').info
及以上的日志才会被处理以进行日志记录。发生这种情况时,控制台将输出所有结果(它将输出所有内容,因为它设置为DEBUG
级别),而mail_admins
记录器将针对所有ERROR
s、FATAL
s 和CRITICAL
s 发生。
我想一些不是 Django 的代码也可能有帮助:
import logging.handlers as hand
import logging as logging
# to make things easier, we'll name all of the logs by the levels
fatal = logging.getLogger('fatal')
warning = logging.getLogger('warning')
info = logging.getLogger('info')
fatal.setLevel(logging.FATAL)
warning.setLevel(logging.WARNING)
info.setLevel(logging.INFO)
fileHandler = hand.RotatingFileHandler('rotating.log')
# notice all three are re-using the same handler.
fatal.addHandler(fileHandler)
warning.addHandler(fileHandler)
info.addHandler(fileHandler)
# the handler should log everything except logging.NOTSET
fileHandler.setLevel(logging.DEBUG)
for logger in [fatal,warning,info]:
for level in ['debug','info','warning','error','fatal']:
method = getattr(logger,level)
method("Debug " + logger.name + " = " + level)
# now, the handler will only do anything for *fatal* messages...
fileHandler.setLevel(logging.FATAL)
for logger in [fatal,warning,info]:
for level in ['debug','info','warning','error','fatal']:
method = getattr(logger,level)
method("Fatal " + logger.name + " = " + level)
这导致:
Debug fatal = fatal
Debug warning = warning
Debug warning = error
Debug warning = fatal
Debug info = info
Debug info = warning
Debug info = error
Debug info = fatal
Fatal fatal = fatal
Fatal warning = fatal
Fatal info = fatal
再次注意在, ,和日志处理程序设置为 时是如何info
记录的,但是当处理程序突然设置为时,只有消息进入文件。info
warning
error
fatal
DEBUG
FATAL
FATAL