"CallbackFilter" can be used to implement Dynamic filepath & filename for in logger config file in python. You can define write_dynamic_log as below:
def write_dynamic_log(record):
now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
dynamic_log_name = '/var/log/test_%s.log' %now
log_file = open(dynamic_log_name, "w")
log_file.write(record.msg)
log_file.close();
return True
Then in the config file, you can use this filter like this:
[handler_filelog]
class: FileHandler
formatter: brief
level : INFO
filters: [write_dynamic_log]
filename: static.log
The INFO or above log will be output to static.log and also to dynamic_log.
I tested it in my django project, in which I wrote config in my settings.py. It works fine. LOGGING will is like:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '[%(levelname)s] %(asctime)s - %(pathname)s:%(lineno)d\n%(message)s'
},
'debug': {
'format': '[%(levelname)s] %(asctime)s - %(pathname)s:%(lineno)d\n\033[34m%(message)s\033[0m'
},
'error': {
'format': 'Component: %(module)s\nErrorCode: %(funcName)s\nReason: %(funcName)s\nDetail: [%(message)s]'
},
},
'filters': {
'write_error_logs': {
'()': 'django.utils.log.CallbackFilter',
'callback': write_error_log,
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
'debug': {
'class': 'logging.StreamHandler',
'formatter': 'debug',
},
'error': {
'level': 'ERROR',
'class': 'logging.FileHandler',
'filename': '/var/log/SmartStorageApp.err',
'formatter': 'error',
'filters': ['write_error_logs'],
},
},
'loggers': {
'django': {
'handlers': ['debug' if DEBUG else 'console', 'error'],
'level': 'INFO',
'propagate': True,
},
}
}