python - 关于 python 日志记录中的 NOTSET

标签 python logging

作为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 levelHandler'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/

相关文章:

php - 如何阻止 PHP 记录 PHP Notice 错误

logging - 有没有办法以编程方式更改日志箱的默认日志记录级别?

python - 从两个可迭代对象创建字典并使用它们

python - 使一个新的字符串变量等于c中的整数变量

python - 从Python在MySql中插入记录时出现错误

logging - 使用Kibana在表中显示2个不同的查询结果

logging - 如何在 golang 中使用并发日志?

python - 在 Python 中, 'return self' 返回对象的副本还是指针?

python - 使用cx_oracle批量下载表

php - 返回对 PHP 中对象的引用