1) logging.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":{
"": { ---root默认,模块名找不到则使用
"level":"INFO",
"handlers":["console","info_file_handler","error_file_handler"],
"propagate":false ---重复日志
},
"module1":{ ---模块名
"level":"INFO",
"handlers":["console","info_file_handler","error_file_handler"],
"propagate":false
},
"module2":{ ---模块名
"level":"INFO",
"handlers":["console","info_file_handler","error_file_handler"],
"propagate":false
}
}
}
2) 初始化
def setup_logging(default_path = "logging.json", default_level = logging.INFO, env_key = "LOG_CFG"):
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
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)
3)使用
kgLogger = logging.getLogger("module1")
kgLogger = logging.getLogger("abc") --调用默认配置
kgLogger.info("This is for test!")