在Python日誌中有兩個不同的概念:日誌記錄的級別和處理程序實際激活的級別。
當由記錄電話,有什麼基本情況是:
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
記錄器將會發生在所有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
消息使其ŧ o文件。
好問題,但一致的緣故,如果你正在測試'a.getEffectiveLevel','a.setLevel'更有感覺比'h.setLevel'。 –
在這種情況下處理程序不具有'getEffectiveLevel'命令 –