将dictConfig()与可变日志文件名一起使用

时间:2020-05-29 11:41:11

标签: python-2.7 logging

我有从以下另一个模块导入的python脚本的配置字典

LOG_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'loggers': {
        '': {
        'handlers': ['consoleHandler', 'fileHandler'],
        'level': 'DEBUG'
    }
},
'handlers': {
    'consoleHandler': {
        'level': 'INFO',
        'formatter': 'consoleFormatter',
        'class': 'logging.StreamHandler',
        'stream': 'ext://sys.stdout',
    },
    'fileHandler': {
        'level': 'INFO',
        'formatter': 'fileFormatter',
        'class': 'logging.FileHandler',
        'mode': 'w',
    }
},
'formatters': {
    'fileFormatter': {
        'format': '%(asctime)s - %(levelname)s -  %(name)s - %(module)s - %(funcName)s - %(message)s',
                    'datefmt': '%Y-%m-%d %H:%M:%S',
                    'class': 'logging.Formatter'
    },
    'consoleFormatter': {
        'format': 'UAC_API>> %(levelname)s - %(message)s'
    },
},

}

我希望日志文件名可变。从文件加载配置时,我使用了:

logging.config.fileConfig(config_file,
                          defaults={'logfilename': logfullpath},
                          disable_existing_loggers=False)

logfullpath是日志文件的路径。

但是defaults={'logfilename': logfullpath}dictConfig不兼容(与logging.config.fileConfig相比只有一种说法)。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

找到解决方法,如果有人遇到相同的问题。由于LOG_CONFIG是我扩展的字典,如下所示(将filename:logfullpath添加为fileHandler的键值对)。然后,我将其用作dictConfig的参数。

LOG_CONFIG['handlers']['fileHandler']['filename'] = logfullpath

logging.config.dictConfig(LOG_CONFIG)