关于python日志记录中的NOTSET [英] About NOTSET in python logging

查看:44
本文介绍了关于python日志记录中的NOTSET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如 logger.setLevel 文件所说:

创建记录器时,级别设置为NOTSET(这将导致在记录器为根记录器时处理所有消息,或者在记录器为非根记录器时委派给父级).请注意,根记录器的创建级别为警告.

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级别的root记录器,则将显示调试和信息日志.

so I think if I create a root logger, with level NOTSET, the debug and info log will display.

代码使用basicConfig将根记录程序的级别设置为NOTSET是正确的:

The code use basicConfig to set root logger's level to NOTSET is right:

#!/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级别的处理程序,例如:

But if I create a root logger, and add handler with NOTSET level to it, such as:

#!/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

但是我认为它也会输出调试和信息消息.

but I think it will also output the debug and info message.

推荐答案

好,我在文档中误解了 Logger的级别 Handler的级别:

OK, I misunderstand the Logger's level and Handler's Level, in the doc:

setLevel()方法(与记录器对象中一样)指定将分派到适当目标的最低严重性.为什么有两个setLevel()方法?在记录器中设置的级别决定了它将传递给其处理程序的消息的严重性.每个处理程序中设置的级别决定了处理程序将继续发送哪些消息.

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.

如果我将代码更改为此,可以:

If I change code to this, will be ok:

#!/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日志记录中的NOTSET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆