在 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's config settings。我将在此处包含相关代码。
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 记录器将发生在所有ERRORs、FATALs 和@987654330 上@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
再次注意,当日志处理程序设置为DEBUG,但当处理程序设置为FATAL 时,info 如何在info、warning、error 和fatal 记录一些内容突然间只有FATAL 消息进入文件。