Python 动态创建导入时记录模块

Python Logging Module when dynamically creating imports

我目前正在使用日志记录 python 模块在编写我的 python 应用程序时记录调试语句。

一切正常,直到我需要记录动态导入 python 模块的语句。

我正在制作的 python 应用程序执行 python 脚本和 returns 这些 python 脚本的结果。将其视为测试 运行ner 及其 运行ning 测试脚本。然而,测试脚本是在 运行 时间通过文件确定的。因此,对于 运行 运行ner 中的脚本,我正在使用 importlib 动态导入它们。

此时一切正常,但我注意到日志记录模块存在一些问题。因为我是在 运行 时间导入代码而不是静态导入代码(静态 = python 模块的开头)。它 "seems" main_script 上的日志记录模块停止,而 side_script 创建一个新的日志记录模块。然后,由于处理程序写入日志而不是追加(按设计),新的日志记录模块会擦除我的日志文件。

一个有趣的注意事项是,只要我在函数 "classically" import Side_Script # NOT at the beginning of the file 中导入另一个模块或动态地重新启动日志记录模块,并且由于写入权限,我当前的日志文件将被删除。不管我 运行 是否导入 python。所以我很确定它不是来自 importlib。

我不确定到底发生了什么。是否可以在函数中动态创建的模块中保持相同的日志记录模块?

我创建了一个基本示例来演示我的问题。请注意,这不是我的实际应用程序,在我的应用程序中,导入的模块在 运行 时间通过文件已知。

Main_Script.py

import logging.config
import importlib

logging.config.fileConfig('Log_Config.conf')

logger = logging.getLogger('simpleExample')

def main():
    logger.info("Logging in the main script.")
    Test_Modulue = importlib.import_module('Side_Script')
    Results = Test_Modulue.Run_Script()

if __name__== "__main__":
    main()

Side_Script.py

import logging.config

logging.config.fileConfig('Log_Config.conf',disable_existing_loggers=False)

logger = logging.getLogger('simpleExample')

def Run_Script():
    logger.info("Logging in the Side script.")

Log_Config.conf

[logger_simpleExample]
level=DEBUG
handlers=consoleDebugCasual,fileHandlerDebugCasual,
qualname=simpleExample
propagate=0

[handler_consoleDebugCasual]
class=StreamHandler
level=DEBUG
formatter=SummaryFormatter
args=(sys.stdout,)

[handler_fileHandlerDebugCasual]
class=FileHandler
level=DEBUG
formatter=SummaryFormatter
args=('Debug_Log.txt','w')

[formatter_SummaryFormatter]
format=%(filename)s-%(lineno)d %(levelname)s: - %(message)s

当前日志输出:

Side_Script.py-8 INFO: - Logging in the Side script.

理想的日志输出:

Main_Script.py-8 INFO: - Logging in the main script.
Side_Script.py-8 INFO: - Logging in the Side script.

是否有像 python 示例中那样保留相同记录器的方法? https://docs.python.org/3.5/howto/logging.html#logging-from-multiple-modules

希望足够详细。

如果我能澄清任何事情,请告诉我。

谢谢!

嗯。我傻傻的。

感谢@Grismar,他发现我加载了两次覆盖了我的日志记录模块的配置。然后删除我的日志,因为它是一个全新的模块。

因此,除了 Side_Script.py 之外,代码的修改将是相同的:

Side_Script.py

import logging.config

logger = logging.getLogger('simpleExample')

def Run_Script():
    logger.info("Logging in the Side script.")

现在的输出是:

Main_Script.py-8 INFO: - Logging in the main script.
Side_Script.py-8 INFO: - Logging in the Side script.