首页 > 解决方案 > 跨子模块记录——如何从子模块访问父记录器名称?

问题描述

我正在尝试将日志记录添加到具有多个模块和子模块的 python 应用程序中。一些网站说要在模块中创建子记录器。我看到的优点是子记录器继承了父记录配置,它将为记录输出(处理程序、格式化程序等)提供一致性。

到目前为止,我正在定义__main__每个类中的类记录器名称并将其与当前类的名称 ( parentName.childName) 连接以获取模块的类记录器。感觉不对,也不可扩展。我该如何改进这一点,这样我就不必__main__在每个类中对类记录器名称进行硬编码?这是我的代码的样子:

我运行的 Py 文件:

###app.py
import logging
from SubModule1 import *

class myApplication():
    loggerName='myAPI'
    def __init__(self, config_item_1=None,config_item_2=None,...config_item_N=None):
        self.logger=self.logConfig()
        self.logger.info("Starting my Application")
        self.object1=mySubClass1(arg1, arg2, ... argM)


    def logConfig(self):
        fileLogFormat='%(asctime)s - %(levelname)s - %(message)s'
        consoleLogFormat='%(asctime)s - %(name)s - %(levelname)s - %(message)s'

        # create logger
        #logger = logging.getLogger(__name__)
        logger = logging.getLogger(self.loggerName)
        logger.setLevel(logging.DEBUG)

        ####CONSOLE HANDLER####
        # create console handler and set level to debug
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)

        # create formatter
        consoleFormatter = logging.Formatter(consoleLogFormat)

        # add formatter to ch
        ch.setFormatter(consoleFormatter)

        # add ch to logger
        logger.addHandler(ch)

        ####FILE HANDLER####
        # create file handler and set level to debug
        fh = logging.FileHandler('API_Log.txt')
        fh.setLevel(logging.DEBUG)

        # create formatter
        fileFormatter = logging.Formatter(fileLogFormat)

        # add formatter to ch
        fh.setFormatter(fileFormatter)

        # add ch to logger
        logger.addHandler(fh)

        logger.info('Logging is started!!')

        return logger

    def connect(self):
        self.logger.info("Connecting to API")
        self.object1.connect()



if __name__=="__main__":
    config={"config_item_1": x,
            "config_item_2": y,
            ...
            "config_item_N": z
            }


    myApp=myApplication(config['config_item_1'],config['config_item_2'],...config['config_item_N'])
    myApp.connect()

模块:

###SubModule1.py
import logging
import app

class mySubClass1():
    appRootLoggerName='myAPI'
    def __init__(self,item1):
        self.logger=logging.getLogger(self.appRootLoggerName + '.'+mySubClass1.__name__)
        self.logger.debug("mySubClass1 object created - mySubClass1")   
        self.classObject1=item1

下面的行是困扰我的行。有什么替代方法self.appRootLoggerName + '.'+mySubClass1.__name__)可以在我的应用程序的模块/类之间共享相同的日志记录配置?

logging.getLogger(self.appRootLoggerName + '.'+mySubClass1.__name__)

标签: pythonloggingmodule

解决方案


推荐阅读