[英]Change log file name in logger module globally
I'm using logger module with dictConfig (with a yaml file) for my application logging. 我正在使用dictConfig(带有yaml文件)的logger模块进行应用程序日志记录。 However, I would to change the log file name globally by adding a date prefix (ex: logpath: /foo/bar/file_20150523.log). 但是,我将通过添加日期前缀来全局更改日志文件名(例如:logpath:/foo/bar/file_20150523.log)。
So each time I start my application a new log file is created. 因此,每次我启动应用程序时,都会创建一个新的日志文件。
Is it possible in one way of another to do it inside the yaml file or I need to modify the handler in my application ? 是否可以以另一种方式在yaml文件中进行操作,或者我需要在应用程序中修改处理程序?
Thanx 谢谢
The idea is simple: 这个想法很简单:
logging.config.dictConfig
and pass in the modified configuration dictionary 调用logging.config.dictConfig
并传入修改后的配置字典 Here is the YAML file I use for this example, daily_log_file.yaml : 这是我用于此示例的YAML文件daily_log_file.yaml :
version: 1
loggers:
default_logger:
handlers: [consoleHandler, fileHandler]
level: DEBUG
handlers:
consoleHandler:
class: logging.StreamHandler
level: DEBUG
formatter: brief
fileHandler:
class: logging.FileHandler
formatter: brief
filename: '/tmp/daily_log_file.log'
level: DEBUG
formatters:
brief:
format: '%(levelname)8s %(message)s'
Here is the script, daily_log_file.py : 这是脚本daily_log_file.py :
import datetime
import os
import logging
import logging.config
import yaml
def yaml_config(yaml_filename):
global config_dict
with open(yaml_filename) as f:
config_dict = yaml.load(f)
# Append the date stamp to the file name
log_filename = config_dict['handlers']['fileHandler']['filename']
base, extension = os.path.splitext(log_filename)
today = datetime.datetime.today()
log_filename = '{}{}{}'.format(
base,
today.strftime('_%Y%m%d'),
extension)
config_dict['handlers']['fileHandler']['filename'] = log_filename
# Apply the configuration
logging.config.dictConfig(config_dict)
if __name__ == '__main__':
yaml_config('daily_log_file.yaml')
logger = logging.getLogger('default_logger')
logger.debug('debug message')
logger.info('info message')
yaml_config
is where the action is. yaml_config
是操作所在的位置。 I first load the configuration dictionary from the YAML file, then patch up the file name 我首先从YAML文件加载配置字典,然后修补文件名 dictConfig
to finish the job 最后,我打电话给dictConfig
完成工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.