简体   繁体   English

记录器对象不继承根级别

[英]logger object not inheriting root level

While experimenting with python's logging module, I came across some unexpected behaviour.在尝试使用 python 的日志模块时,我遇到了一些意想不到的行为。 My guess is that this is due to my misunderstanding, rather than a bug, but I can't figure out what's wrong (and I've been careful to restart the python kernel before testing, to ensure that the root logger is only configured once.我的猜测是这是由于我的误解,而不是错误,但我无法弄清楚出了什么问题(并且在测试之前我已经小心地重新启动了python内核,以确保根记录器只配置一次.

import logging
logging.basicConfig(level=logging.CRITICAL)
logger1 = logging.getLogger(__name__)
logger1.debug("logger1 debug test")

As expected, the logging message is not output.正如预期的那样,不会输出日志消息。

If I then change the level of the logger as follows:如果我然后按如下方式更改记录器的级别:

logger1.setLevel('DEBUG')
logger1.debug("logger1 debug test")

I get the expected output:我得到预期的输出:

DEBUG:__main__:logger1 debug test

However, when I now create a new logger object, it seems to have inherited the properties of logger1, rather than of root:但是,当我现在创建一个新的 logger 对象时,它似乎继承了 logger1 的属性,而不是 root 的:

logger2 = logging.getLogger(__name__)
logger2.debug("logger2 debug test")

which produces:它产生:

DEBUG:__main__:logger2 debug test

Weirdly, logger2 still shows the root as the parent, yet shows a level of 10:奇怪的是,logger2 仍然将根显示为父级,但显示级别为 10:

print(logger2.__dict__)

{'filters': [], 'name': '__main__', 'level': 10, 'parent': <RootLogger root (CRITICAL)>, 'propagate': True, 'handlers': [], 'disabled': False, '_cache': {10: True}, 'manager': <logging.Manager object at 0x00000265147F2B48>}

Can anyone please explain why logger2 isn't defaulting to a level of 0 (NOTSET)?任何人都可以解释为什么 logger2 没有默认为 0 (NOTSET) 级别?

Thanks to @Abhinav Mathur for the answer provided in the comments.感谢@Abhinav Mathur 在评论中提供的答案。

The issue was that by attempting to create logger2 with the same name as logger1, I was in effect not creating a new logger object.问题是,通过尝试创建与 logger1 同名的 logger2,我实际上并没有创建新的 logger 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM