Python日志消息格式不适用于子模块消息

时间:2019-03-08 14:44:32

标签: python logging module formatting

我正在尝试将日志记录添加到我的应用程序中,但是无法将格式应用于我的应用程序的子模块的日志消息中……我在很多地方都建议为记录器分配模块的名称(__name__,但这似乎还不够……

主模块:

####test_logging_modules.py

import logging
from test_logging_module1 import *

class myApplication():
    def __init__(self):
        self.logger=self.logConfig()
        print("Logger name is:")
        print(self.logger.name)
        self.logger.info("Creating a new App")
        print("here is a new App")
        self.attribute1=moduleLogObject()


    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.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('myApp_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




if __name__=="__main__":
    print("This is main!")

    myApp=myApplication()

子模块:

###test_logging_module1.py
import logging

class moduleLogObject():
    def __init__(self):
        self.logger=logging.getLogger(__name__)
        print("Logger name is:")
        print(self.logger.name)
        self.logger.info("Object is initializing - INFO")
        self.logger.warning("Object is really initializing - WARNING")
        logging.info("Logging says Object is initializing - INFO")
        logging.warning("Logging says Object is really initializing - WARNING")

输出:

This is main!
2019-03-08 06:20:03,456 - __main__ - INFO - Logging is started!!
Logger name is:
__main__
2019-03-08 06:20:03,568 - __main__ - INFO - Creating a new App
here is a new App
Logger name is:
test_logging_module1
Object is really initializing - WARNING
WARNING:root:Logging says Object is really initializing - WARNING

顶部模块的日志消息正确显示,包括时间戳,模块名称,日志级别和日志消息:

2019-03-08 06:20:03,456 - __main__ - INFO - Logging is started!!
2019-03-08 06:20:03,568 - __main__ - INFO - Creating a new App

另一方面,来自子模块的日志消息似乎具有默认格式:

Object is really initializing - WARNING
WARNING:root:Logging says Object is really initializing – WARNING

我缺少将配置的格式一致地应用于主模块和所有下游子模块的功能吗?

0 个答案:

没有答案