gpt4 book ai didi

简单示例的 Python 日志记录问题

转载 作者:太空宇宙 更新时间:2023-11-04 00:39:28 25 4
gpt4 key购买 nike

我尝试了一个基于官方 Logging Cookbook 的简单示例,但结果出乎意料:

LOG_PATH = 'logs'

logger = logging.getLogger(__name__)

# Creates 2 Handlers to split log levels
info_fh = logging.FileHandler(path.join(LOG_PATH, 'info_level.log'))
info_fh.setLevel(logging.INFO)
err_fh = logging.FileHandler(path.join(LOG_PATH, 'err_level.log'))
err_fh.setLevel(logging.ERROR)

# Create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
info_fh.setFormatter(formatter)
err_fh.setFormatter(formatter)

# add the handlers to logger
logger.addHandler(info_fh)
logger.addHandler(err_fh)

然后我在控制台中写:

In [2]: logger.info("hello")
In [3]: logger.error("bad")

后来:

cat logs/err_level.log
>>> 2017-02-27 13:16:40,328 - jive - ERROR - bad

cat logs/info_level.log
>>> 2017-02-27 13:16:40,328 - jive - ERROR - bad

我不明白为什么 info_level.log 文件不包含“hello”日志记录。

最佳答案

这可能意味着您的logger 自身的级别高于logging.INFO (20)。该值继承自父记录器:

>>> logger.level  
0 # that means it is not set
>>> logging.NOTSET
0
>>> logger.getEffectiveLevel()
30 # value of parent because not set
>>> logger.parent.level
30
>>> logging.INFO
20 # < logger.getEffectiveLevel() -> not picked up

手动设置记录器的级别:

>>> logger.setLevel(logging.DEBUG)
>>> logger.getEffectiveLevel()
10

现在 info 日志将被提取。来自 Logger.getEffectiveLevel docs :

Indicates the effective level for this logger. If a value other than NOTSET has been set using setLevel(), it is returned. Otherwise, the hierarchy is traversed towards the root until a value other than NOTSET is found, and that value is returned

其他地方:

Note that the root logger is created with level WARNING.

关于简单示例的 Python 日志记录问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42486859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com