【问题标题】:Logs are getting added to both defult and customer file appender日志被添加到默认和自定义文件附加程序中
【发布时间】:2021-03-02 16:52:15
【问题描述】:

我编写了一个日志记录实用程序,其中有一个默认记录器(比如说 L1),它是从 logconfig.yaml 文件初始化的,当使用 L1 时,日志将写入“l1_logfile.log”。此外,我还定义了另一个记录器(比如 L2),它有自己的 appender 处理程序,这样在使用 L2 时,日志消息会写入文件“l2_logfile.log”。

使用以下静态配置(来自 logconfig.yaml 文件)初始化 L1 记录器,并使用 --logging.config.dictConfig(config) 进行初始化。

version: 1

formatters:
  json_formatter:
    format: '%(asctime)s %(levelname)s [%(threadName)s] %(name)s %(filename)s:%(funcName)s %(message)s'
    class: pythonjsonlogger.jsonlogger.JsonFormatter

handlers:
  file_handler:
    class: logging.handlers.RotatingFileHandler
    formatter: json_formatter
    filename: ../logs/logfile.log
    maxBytes: 10485760 # 10MB
    backupCount: 20

loggers:
  my_module:
    level: DEBUG
    handlers: [file_handler]
    propagate: no

root:
  level: DEBUG
  handlers: [file_handler]

L1 记录器及其配置器如下所示。

def setup_logging(path):
    with open(path, 'rt') as f:
        try:
            multiprocessing_logging.install_mp_handler()
            config = yaml.safe_load(f.read())
            logging.config.dictConfig(config)
        except Exception as e:
            print('Error in Logging Configuration. Using default configs')
            logging.basicConfig(filemode='w', level=DEFAULT_LOG_LEVEL)

L2 记录器是一个动态记录器配置,还有一个自定义文件追加器。

def get_custom_logger_appender(appender_name, logger_name):
    logr_name = appender_name + logger_name
    logger = logging.getLogger(logr_name)
    format_str = '%(asctime)s %(levelname)s [%(threadName)s] %(name)s %(filename)s:%(funcName)s %(message)s'
    formatter = jsonlogger.JsonFormatter(format_str)
    log_file_name = os.path.join("./logs", '{}_{}.log'.format(appender_name, "appln"))
    file_handler = logging.handlers.RotatingFileHandler(log_file_name,
                                                            maxBytes=100000,
                                                            backupCount=15)

    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.DEBUG)
    logger.addHandler(file_handler)
    logger.setLevel(logging.DEBUG)
    adapter = CustomAdapter(logger, {'app_context': "app_context_value"})
    return adapter

这是一个单元测试函数。

class TestSum(unittest.TestCase):
    // Defualt configurator.
    setup_logging("./logconfig.yaml")
    
    def test_appender_log_file_created(self):
        appender_name = "appender"
        logger_name = "testlogger"
        self.logger = Logger.get_custom_logger_appender(appender_name, logger_name)
        self.logger.info("This is info log 1")
        self.logger.info("This is info log 2")
        self.logger.info("This is info log 3")
        base_dir = self.logger_config.log_base_dir()
        log_file = base_dir + "/" + appender_name + '_' + LoggerConfig.appl_name() + ".log"
        assert os.path.exists(log_file)

问题是三个日志消息被写入日志文件“l1_logfile.log”和“l2_logfile.log”,而这些日志消息应该只写入“l2_logfile.log”,因为它们是由自定义记录器附加程序写入的.我的逻辑有什么问题?

【问题讨论】:

    标签: python python-3.x logging


    【解决方案1】:

    我通过使用另一个 RotatingFileHandler 实现 get_logger() 解决了这个问题。问题是记录器配置(使用 .yaml 文件)也被默认应用于 L2 记录器实例。下面的代码有助于显式配置记录器。

    def get_logger(logger_name):
      log_file_name = os.path.join("logfile.log")
      file_handler = logging.handlers.RotatingFileHandler(log_file_name,
                                                          mode='a',
                                                          maxBytes=10*1024*1024,
                                                          backupCount=15)
      formatter = jsonlogger.JsonFormatter('%(asctime)s %(levelname)s [%(threadName)s] %(name)s %(filename)s:%(funcName)s %(message)s')
      file_handler.setFormatter(formatter)
      logger = logging.getLogger(logger_name)
      logger.setLevel(logging.DEBUG)
      logger.addHandler(file_handler)
      adapter = CustomAdapter(logger, {'app_context': "app_context"})
      Logger.__logger_dict[logger_name] = adapter
    
      Logger.update_log_level_config(logger_name, logger.level)
      return adapter
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-30
      • 1970-01-01
      • 2018-09-17
      • 1970-01-01
      相关资源
      最近更新 更多