gpt4 book ai didi

python logger - 只能运行一次

转载 作者:行者123 更新时间:2023-11-28 22:28:01 25 4
gpt4 key购买 nike

我正在使用 jupyter notebook 测试 python 记录器。

当我在新启动的内核中运行以下示例代码时,它可以正常工作并创建具有正确内容的日志文件。

import logging
logging.basicConfig(filename='/home/depot/wintergreen/example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

但是,如果我尝试重新运行相同的代码,例如,文件名从 example.log 更改为 example.log2,什么也没有发生,文件 example.log2 未创建。

我最终设计了该测试,因为在我看来,当尝试运行日志记录时,它只会在我第一次运行它时起作用。我在这里做错了什么?

最佳答案

你是对的,.basicConfig() 只使用了一次你的kwargs。因为在第一次获得处理程序 logging.root.handlers 之后,实际上是一个处理程序,所以如果您查看 source code

def basicConfig(**kwargs):
...
_acquireLock()
try:
if len(root.handlers) == 0:
...
finally:
_releaseLock()

因此,由于您的 len(root.handlers) != 0 所提供参数的实际赋值并未发生。

如何在不重新启动的情况下进行更改:

我想到的唯一解决方案是通过调用 .basicConfig() 来更改基本配置而不重新启动内核:

for handler in logging.root.handlers:
logging.root.removeHandler(handler)

这将从根记录器中删除所有处理程序,之后您可以设置任何您想要的。

关于python logger - 只能运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43825712/

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