Using dictConfig() with variable log file name

Viewed 972

I have configuration dictionary for python scripts that I import from another module like below

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'
    },
},

}

I want log filename to be variable. When loading configuration from a file, I used:

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

Where logfullpath is path to the log file.

But defaults={'logfilename': logfullpath} does not work with dictConfig (comparing to logging.config.fileConfig has just one agument). Would anybody help me with that please?

1 Answers

Found a workaround if anyone has the same problem. Since the LOG_CONFIG is the dictionary I expanded it like can be seen below (added filename:logfullpath as key value pair for fileHandler). Then I used it as argument for dictConfig.

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

logging.config.dictConfig(LOG_CONFIG)
Related