[英]Set Python Logging to overwrite log file when using dictConfig?
I'm using dictConfig()
to configure my logging. 我正在使用
dictConfig()
配置日志记录。 I want the process to overwrite the specified log file every time the process is run. 我希望该进程每次运行时都覆盖指定的日志文件。 How do I do this?
我该怎么做呢?
I see filemode
as a setting in basicConfig()
but I can't figure out where to put this in the dictConfig()
configuration. 我将
filemode
视为basicConfig()
的设置,但是我不知道将其放在dictConfig()
配置中的位置。
I've tried this but get an unexpected keyword argument 'filemode'
error. 我已经尝试过了,但是出现了
unexpected keyword argument 'filemode'
错误。 I've tried it in a few other places too. 我也在其他一些地方尝试过。 Python logging docs are confusing as hell!
Python日志记录文档令人困惑!
LOG_PATH = os.path.join(PROJECT_PATH,'logs')
LOG_FILE_NAME = 'log.'+main.__file__+'.'+time.strftime("%Y-%m-%d")
LOG_FILE_PATH = os.path.join(LOG_PATH,LOG_FILE_NAME)
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '[%(levelname)s] %(message)s - [pid:%(process)d - %(asctime)s - %(name)s]',
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'formatter': 'standard',
'class': 'logging.StreamHandler',
},
'file': {
'level': 'INFO',
'formatter': 'standard',
'class': 'logging.FileHandler',
'filename': LOG_FILE_PATH,
'filemode': 'w',
},
},
'loggers': {
'': {
'handlers': ['console','file'],
'level': 'DEBUG',
'propagate': True
},
},
}
logging.config.dictConfig(os.path.join(LOGGING_CONFIG))
logger = logging.getLogger(__name__)
logger.debug('logger configured')
ANSWER 回答
Thanks to @Vinay Sajip for his selected answer below. 感谢@Vinay Sajip在下面选择的答案。 Here is my updated configuration that now overwrites the specified log file every time the process is run.
这是我更新的配置,现在每次运行该进程时都会覆盖指定的日志文件。 I simply added
LOGGING_CONFIG['handlers']['file']['mode'] = 'w'
. 我只是添加了
LOGGING_CONFIG['handlers']['file']['mode'] = 'w'
。
LOG_PATH = os.path.join(PROJECT_PATH,'logs')
LOG_FILE_NAME = 'log.'+main.__file__+'.'+time.strftime("%Y-%m-%d")
LOG_FILE_PATH = os.path.join(LOG_PATH,LOG_FILE_NAME)
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '[%(levelname)s] %(message)s - [pid:%(process)d - %(asctime)s - %(name)s]',
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'formatter': 'standard',
'class': 'logging.StreamHandler',
},
'file': {
'level': 'INFO',
'formatter': 'standard',
'class': 'logging.FileHandler',
'filename': LOG_FILE_PATH,
'mode': 'w', # <=== HERE IS THE CHANGE
},
},
'loggers': {
'': {
'handlers': ['console','file'],
'level': 'DEBUG',
'propagate': True
},
},
}
logging.config.dictConfig(os.path.join(LOGGING_CONFIG))
logger = logging.getLogger(__name__)
logger.debug('logger configured')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.