python 日志 logging模块
背景
使用print,无法打印日志的级别错误,故用logging模块
彩色打印
import logging
# logger = logging.getLogger('your-module')
# Initialize coloredlogs.
import coloredlogs
coloredlogs.install(level='DEBUG')
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
通过JSON文件配置
json配置文件
{
"version":1,
"disable_existing_loggers":false,
"formatters":{
"simple":{
"format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
},
"handlers":{
"console":{
"class":"logging.StreamHandler",
"level":"DEBUG",
"formatter":"simple",
"stream":"ext://sys.stdout"
},
"info_file_handler":{
"class":"logging.handlers.RotatingFileHandler",
"level":"INFO",
"formatter":"simple",
"filename":"info.log",
"maxBytes":"10485760",
"backupCount":20,
"encoding":"utf8"
},
"error_file_handler":{
"class":"logging.handlers.RotatingFileHandler",
"level":"ERROR",
"formatter":"simple",
"filename":"errors.log",
"maxBytes":10485760,
"backupCount":20,
"encoding":"utf8"
}
},
"loggers":{
"my_module":{
"level":"ERROR",
"handlers":["info_file_handler"],
"propagate":"no"
}
},
"root":{
"level":"INFO",
"handlers":["console","info_file_handler","error_file_handler"]
}
}
通过JSON加载配置文件,然后通过logging.dictConfig配置logging,
import json
import logging.config
import os
def setup_logging(default_path = "logging_config.json",info_file='info.log',errors_file='errors.log',default_level = logging.INFO,env_key = "LOG_CFG"):
path = default_path
value = os.getenv(env_key,None)
config = None
if value:
path = value
if os.path.exists(path):
with open(path,"r") as f:
config = json.load(f)
if config:
config['handlers']['info_file_handler']['filename'] = info_file
config['handlers']['error_file_handler']['filename'] = errors_file
with open(path,"w") as f:
json.dump(config, f)
print('config---',config)
with open(path,"r") as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level = default_level)
def func():
logging.info("start func")
logging.warning("exec func")
logging.info("end func")
if __name__ == "__main__":
setup_logging(info_file='a.log',errors_file='e.log')
func()
后期info_file和errors_file可配置使用