【问题标题】:Level set in logging.basicConfig does not have the expected effect在 logging.basicConfig 中设置的级别没有预期的效果
【发布时间】:2015-10-07 08:12:29
【问题描述】:

Python 的 logging.basicConfig 的行为与我预期的不同。在下面的代码中,使用logging.warn 发送的消息即使我调用basicConfig 的级别为ERROR 也会被发送。

import logging

logging.basicConfig(level=logging.ERROR)
root = logging.getLogger()
print("root.level", logging.getLevelName(root.level))
print("Levels for root.handlers: {}".format(
        [logging.getLevelName(handler.level) for handler in root.handlers]))
logging.warn("You're seeing this even though you called basicConfig with level=logging.ERROR")
root.warn("You're seeing this too")

root.setLevel(logging.ERROR)
logging.warn("But you won't see this")

产生的输出是

root.level WARNING
Levels for root.handlers: ['NOTSET']
WARNING:root:You're seeing this even though you called basicConfig with level=logging.ERROR
WARNING:root:You're seeing this too

请注意,一旦我自己调用了root.setLevel,对logging.warn 的最终调用确实无法按预期产生输出。

如果logging.basicConfig 的level 参数在这个简单的设置中不起作用,它有什么用?如果我想控制在一个简单的设置中输出什么级别的消息,那么调用root.setLevel 的首选方法是什么?

这是我的版本信息:

# sys.version = 3.4.3 |Continuum Analytics, Inc.| (default, Mar  6 2015, 12:03:53) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]

stackoverflow 上已经有几个问题似乎与这个问题相同,但我发现的所有问题实际上都是关于其他事情的:

  1. This guy 正在尝试运行 logging.basicConfig 在他已经完成一些日志记录之后
  2. This question 尝试多次调用 logging.basicConfig(产生类似于 #1 的效果)
  3. This question 涉及使用子记录器

【问题讨论】:

  • 使用上面的确切代码,我无法用 python 2.7 或 3.4 复制它。

标签: python logging


【解决方案1】:

使用给定的代码,我无法复制您的问题。相反,输出符合预期。

root.level ERROR
Levels for root.handlers: ['NOTSET']

您是否有可能在启动时由 python 调用 sitecustomize.py 或 usercustomize.py?这些通常用于提供日志记录设置。

如果根处理程序已经初始化,函数basicConfig 什么都不做。因此,如果您已经有这样的文件在进行设置,那么第二次 basicConfig 调用将是无操作的。

尝试使用以下任一方式运行您的代码:

python3.4 -I 

或

python2.7 -ES

这些标志将有助于隔离您的环境并防止导入 site(然后导入 sitecustomize 等)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-06
    • 2018-06-30
    • 2017-07-12
    • 1970-01-01
    • 2020-12-31
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多