PYTHON使用LOGGING配置文件
代码
# -*- coding: utf-8 -*-
import sys
import json
import logging
import logging.config
import traceback
if __name__ == '__main__':
configure = './template/log/config.json'
log = logging.getLogger('root')
try:
with open(configure, 'r', encoding='utf-8') as file:
logging.config.dictConfig(json.load(file))
raise Exception('This is an actively thrown exception')
except Exception:
log.critical('Exception content: \n{}'.format(traceback.format_exc()))
sys.exit(0)
配置
{
"version":1,
"disable_existing_loggers":false,
"formatters":{
"standard":{
"format":"[%(asctime)s.%(msecs)03d][%(levelname)s][%(filename)s:%(lineno)d] >> %(message)s",
"datefmt":"%Y-%m-%d %H:%M:%S"
}
},
"handlers":{
"console":{
"class":"logging.StreamHandler",
"level":"INFO",
"formatter":"standard",
"stream":"ext://sys.stdout"
},
"file":{
"class":"logging.handlers.TimedRotatingFileHandler",
"level":"DEBUG",
"formatter":"standard",
"filename":"./logging.log",
"when":"midnight",
"encoding":"utf8"
}
},
"root":{
"level":"INFO",
"handlers":["console","file"]
}
}
说明
创建日志的实例,调用配置接口完成全局配置,已存在的实例会执行最新配置。
输出
[2021-01-05 19:42:01.953][CRITICAL][main.py:17] >> Exception content:
Traceback (most recent call last):
File "main.py", line 15, in <module>
raise Exception('This is an actively thrown exception')
Exception: This is an actively thrown exception