logconfig.json
{
"version":1,
"disable_existing_loggers":false,
"formatters":{
"simple":{
"format":"[%(asctime)s - %(levelname)s - line(%(lineno)d) - %(filename)s]: %(message)s",
"datefmt":"%Y-%m-%d %H:%M:%S"
}
},
"handlers":{
"console":{
"class":"logging.StreamHandler",
"level":"DEBUG",
"formatter":"simple",
"stream":"ext://sys.stdout"
},
"info_file_handler":{
"class":"logging.handlers.TimedRotatingFileHandler",
"level":"INFO",
"formatter":"simple",
"filename":"../log/info.log",
"when":"H",
"interval":1,
"backupCount":50,
"encoding":"utf8"
},
"error_file_handler":{
"class":"logging.handlers.TimedRotatingFileHandler",
"level":"ERROR",
"formatter":"simple",
"filename":"../log/errors.log",
"when":"H",
"interval":1,
"backupCount":50,
"encoding":"utf8"
}
},
"loggers":{
"my_module":{
"level":"ERROR",
"handlers":["info_file_handler"],
"propagate":"no"
}
},
"root":{
"level":"INFO",
"handlers":["console","info_file_handler","error_file_handler"]
}
}
log_utility.py
import os
import json
import logging
import logging.config
def setup_logging(default_path="logconfig.json",default_level=logging.DEBUG):
path = default_path
if os.path.exists(path):
with open(path,"r") as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
调用
config_path = sys.path[0] + '/logconfig.json'
log_utility.setup_logging(config_path)