2

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

一切都很好,直到我需要从动态导入 python 模块中记录语句。

我正在制作的 python 应用程序执行 python 脚本并从这些 python 脚本返回结果。把它想象成一个测试运行器和它正在运行的测试脚本。然而,测试脚本是在运行时通过文件确定的。因此,为了在运行程序中运行脚本,我使用 importlib 动态导入它们。

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

一个有趣的注意事项是,只要我“经典”import Side_Script # NOT at the beginning of the file或动态地在函数中导入另一个模块,Logging 模块就会重新启动,并且我当前的日志文件由于写权限而被删除。无论我是否运行 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.

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

希望这是足够的细节。

让我知道我是否可以澄清任何事情。

谢谢!

4

1 回答 1

0

好。我傻傻了。

感谢@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.
于 2019-03-12T02:32:03.650 回答