Python Logging StreamHandler 不是从模块记录的



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

program.py,support_module1.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完美地解释了修复的原因和方法。非常感谢。

在program.py中,您正在配置logging.getLogger(名称(。这将只影响名为program.py的记录器,因此只影响program.py本身内的日志记录。module1.py中的logging.getLogger(名称(将返回一个名为module1.pi的不同记录器,该记录器不受程序.py中配置的影响。修复方法非常简单-将logging.getLogger(名称(替换为程序.py的logging.getLogger((。这将配置根记录器。-hoefling

最新更新