我正在尝试让 Python 记录内容,尽管已经阅读了 logging docs和 how-to ,我不明白它的行为。
我设置了全局日志级别,然后尝试记录一些东西:
logger = logging.getLogger()
print("Initially should be warn: %d" % logger.getEffectiveLevel())
logger.setLevel(logging.DEBUG)
print("Logger level: %d" % logger.getEffectiveLevel())
logger.info("Maybe I am printed?")
但是运行 python my_script.py
只是打印:
Initially should be warn: 30
Logger level: 10
但是,如果我添加一行 logging.info
调用,例如,
logger = logging.getLogger()
print("Initially should be warn: %d" % logger.getEffectiveLevel())
logger.setLevel(logging.DEBUG)
print("Logger level: %d" % logger.getEffectiveLevel())
logging.info("I am printed")
logger.info("Maybe I am printed?")
然后日志全部显示出来:
Initially should be warn: 30
Logger level: 10
INFO:root:I am printed
INFO:root:Maybe I am printed?
logging.info
在做什么?
最佳答案
第一个示例实际上会警告您找不到记录器“root”的处理程序(see here)。这是因为,如建议的那样,您没有为定义任何处理程序记录器
。
下面是logging.info
的实现:
def info(msg, *args, **kwargs):
"""
Log a message with severity 'INFO' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
root.info(msg, *args, **kwargs)
如您所见,当未找到处理程序时,它将调用 basicConfig
,它还将负责初始化默认处理程序,从而修复您后续语句中的日志记录。
关于python - 为什么调用 logging.info 会改变我的记录器打印的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46568454/