来自多个模块的Python日志记录问题

2024-04-27 13:59:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有3个python模块。

LogManager.py
Runner.py
Other.py

Runner.py是事件链中的第一个主模块,并从该模块调用Other.py中的函数。

所以,在Runner.py内部,我有一个函数调用LogManager.py

logger = LogManager.get_log()

从那里,我可以制作简单的日志,例如logger.critical("OHNOES")

我希望get_log函数做的是类似于singleton模式的事情,在这种模式下,如果没有设置记录器,它将设置记录器并返回它。否则,它只会返回记录器。

LogManager.py的内容:

import logging

def get_log():
    logger = logging.getLogger('PyPro')
    logger.setLevel(logging.DEBUG)

    # create file handler which logs even debug messages
    fh = logging.FileHandler('pypro.log')
    fh.setLevel(logging.DEBUG)

    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.WARNING)

    # create formatter and add it to the handlers
    fhFormatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    chFormatter = logging.Formatter('%(levelname)s - %(filename)s - Line: %(lineno)d - %(message)s')
    fh.setFormatter(fhFormatter)
    ch.setFormatter(chFormatter)

    # add the handlers to logger
    logger.addHandler(ch)
    logger.addHandler(fh)

    logger.info("-----------------------------------")
    logger.info("Log system successfully initialised")
    logger.info("-----------------------------------")

    return logger

如您所见,LogManager.get_log()将在每次调用日志时尝试设置日志。真的,我有点困惑到底发生了什么。。。

Runner.py在其main方法中调用get_log函数。 Other.py在全局范围内调用get_日志(在导入之后,不在任何函数中)

结果是,我生成的所有日志都被记录两次,而日志记录器的处理程序则被记录两次。

我缺少什么最简单的方法使get_log函数返回同一个日志elsewise的实例?


Tags: 模块函数pyloggetloggingcreatech