作为logger.setLevel医生说:
When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with level WARNING.
所以我想如果我创建一个根记录器,级别为 NOTSET,就会显示调试和信息日志。
使用basicConfig 将root logger 的级别设置为NOTSET 的代码是正确的:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logging.basicConfig(level=logging.NOTSET)
log = logging.getLogger()
log.debug('debug')
log.info('info')
log.warning('warning')
log.error('error')
log.critical('critical')
输出为:
DEBUG:root:debug
INFO:root:info
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical
但是如果我创建一个根记录器,并向它添加 NOTSET 级别的处理程序,例如:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
log = logging.getLogger()
hd = logging.StreamHandler()
hd.setLevel(logging.NOTSET)
log.addHandler(hd)
log.debug('debug')
log.info('info')
log.warning('warning')
log.error('error')
log.critical('critical')
输出是:
warning
error
critical
但我认为它还会输出调试和信息消息。
最佳答案
好吧,我误解了文档中的Logger's level
和Handler's Level
:
The setLevel() method, just as in logger objects, specifies the lowest severity that will be dispatched to the appropriate destination. Why are there two setLevel() methods? The level set in the logger determines which severity of messages it will pass to its handlers. The level set in each handler determines which messages that handler will send on.
如果我把代码改成这样,就可以了:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
log = logging.getLogger()
log.setLevel(logging.NOTSET) # Set Logger's level to NOTSET, default is WARNING
#print "Logger's Level: ", log.level
hd = logging.StreamHandler()
hd.setLevel(logging.NOTSET)
#print "Handler's Level: ", hd.level
log.addHandler(hd)
log.debug('debug')
log.info('info')
log.warning('warning')
log.error('error')
log.critical('critical')
关于python - 关于 python 日志记录中的 NOTSET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21494468/