我将以下 dictConfig 用于记录器。但是,我无法在运行时修改日志记录级别。
#log_config.json 的内容
{
"version": 1,
"disable_existing_loggers": false,
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)-12s - %(levelname)-8s - %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S"
},
"detailed": {
"format": "%(asctime)s %(name)-12s %(module)-17s line:%(lineno)-4d %(levelname)-8s %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "INFO",
"formatter": "simple",
"stream": "ext://sys.stdout"
},
"info_file_handler": {
"class": "logging.handlers.TimedRotatingFileHandler",
"level": "INFO",
"formatter": "detailed",
"filename": "info.log",
"when": "midnight",
"backupCount": 7,
"encoding": "utf8"
},
"error_file_handler": {
"class": "logging.handlers.TimedRotatingFileHandler",
"level": "ERROR",
"formatter": "detailed",
"filename": "errors.log",
"when": "midnight",
"backupCount": 7,
"encoding": "utf8"
}
},
"loggers": {
"": {
"level": "ERROR",
"handlers": ["console"],
"propagate": "no"
}
},
"root": {
"level": "NOTSET",
"handlers": ["console", "info_file_handler", "error_file_handler"]
}
}
然后我获取记录器并使用以下方法设置级别:
with open('/path/to/log_config.json', 'r') as fd:
cfg = json.load(fd)
logging.config.dictConfig(cfg)
logger = logging.getLogger(__name__)
logger.setLevel(10)
但是,因为记录器是使用 dictConfig 创建的,所以我无法覆盖级别。我想构建一个 UI 工具,它有一个选项菜单,可以在运行时调整日志记录级别,而无需破解打开的代码或 json 文件进行调整。我可以将级别调高,但由于某种原因它不会让级别降低...
我想做的是在配置中将 info_file 和控制台处理程序设置为 INFO (20),然后可以选择在运行时将它们更改为 DEBUG (10)。有任何想法吗?