如何使在主模块中创建的自定义适配器可用于所有模块

时间:2019-01-08 13:26:17

标签: python logging

我编写了一个自定义适配器,以将额外的值传递给我在python主代码类中的日志记录 因此,我想在所有模块中都添加到我的记录器的额外字段,而不必再为每个功能编写自定义适配器,并且我还希望在日志记录中的INFO之后打印额外的变量

我正在使用json记录配置并将其加载到主类中

JSON配置:

{
"version": 1,
"disable_existing_loggers": false,
"formatters": {
    "standard": {
        "format": "%(asctime)s [%(levelname)s] %(funcName)s: %(message)s"
    }
},
"handlers": {
    "console": {
        "level":"DEBUG",
        "class":"logging.StreamHandler",
        "formatter": "standard",
        "stream": "ext://sys.stdout"
    },
    "info_file": {
        "class": "logging.handlers.RotatingFileHandler",
        "level": "INFO",
        "formatter": "standard",
        "filename": "info.log",
        "maxBytes": 10485760,
        "backupCount": 15,
        "encoding": "utf8"
    },
    "error_file": {
        "class": "logging.handlers.RotatingFileHandler",
        "level": "ERROR",
        "formatter": "standard",
        "filename": "error.log",
        "maxBytes": 10485760,
        "backupCount": 20,
        "encoding": "utf8"
    }
},
"root": {
    "handlers": [ "info_file"],
    "level": "DEBUG"
}

}

主类:

if __name__ == "__main__":
      logger = logging.getLogger(__name__)

    with open(base_dir_path+'logging_conf.json', 'r') as logging_configuration_file:
    config_dict = json.load(logging_configuration_file)
logging.config.dictConfig(config_dict)

并通过从另一个模块导入来创建CustomAdapter

class CustomAdapter(logging.LoggerAdapter):
    def process(self, msg, kwargs):
        # use log_context from kwargs or the default given on instantiation
       log_context = kwargs.pop('log_context', self.extra['log_context'])
       return '[%s] %s' % (log_context, msg), kwargs

 log_id = '123'
 extra = {'log_context': log_id}
     logger = CustomAdapter(logger, extra)
     logger.info(log_id)

对于不同模块中的每个函数,我都传递日志ID并调用CustomAdapter

def somemethod(log_id)
   logger = logging.getLogger(__name__)
   logger = CustomAdapter(logger, extra= {'log_context': log_id})

记录器输出:

2019-01-08 23:57:23,901 [INFO] check_for_last_run_in_job_control: [123] Executing query to check if last run is INPROGRESS

记录器输出除外:

  2019-01-08 23:57:23,901 [INFO] [123] check_for_last_run_in_job_control: Executing query to check if last run is INPROGRESS

1。因此,对于每种方法,我都传递我的日志ID并导入CustomAdapter,通过传递给每个函数,我们可以使它在所有模块中都可用

  1. 而且我也希望我的自定义记录器文件在INFO之后显示

0 个答案:

没有答案