gpt4 book ai didi

Python 日志记录 StreamHandler 不从模块记录日志

转载 作者:行者123 更新时间:2023-12-01 08:39:42 25 4
gpt4 key购买 nike

我有一个非常简单的结构。但我的两个日志处理程序中只有一个正在从我的模块进行日志记录:

程序.py,支持模块1.py,support_module2.py

#program.py
import support_module1 as SM1
import support_module1 as SM2
log = logging.getLogger(__name__)
logging.basicConfig(
filename='/logs/TestLog.log',
filemode='w',
level='DEBUG',
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[logging.FileHandler(r'/logs/TestLog.log')])
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.INFO)
log.addHandler(stdout_handler)

log.debug("shows in file")
log.info("shows in file and in stdout")
SM1.function1()
SM2.function2()

模块

#support_module1.py
mod1_log = logging.getLogger(__name__)

function1():
mod1_log.debug("shows in file")
mod1_log.info("should show in file and in stdout, but only goes to file")


#support_module2.py
mod2_log = logging.getLogger(__name__)

function2():
mod2_log.debug("shows in file")
mod2_log.info("should show in file and in stdout, but only goes to file")

当我运行时,我得到:

shows in file and in stdout

我期待:

shows in file and in stdout
should show in file and in stdout, but only goes to file
should show in file and in stdout, but only goes to file

有人告诉我我做错了什么吗?

最佳答案

hoefling 完美地解释了原因以及如何解决。谢谢!

In program.py, you are configuring logging.getLogger(name). This will affect only the logger named program.py and thus only log records inside program.py itself. The logging.getLogger(name) inside module1.py will return a different logger named module1.py which is unaffected by the configuration in program.py The fix is very simple - replace logging.getLogger(name) with logging.getLogger() in program.py. This will configure the root logger instead. -hoefling

关于Python 日志记录 StreamHandler 不从模块记录日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53563573/

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