我们在编写Python日志脚本的时候经常会需要将脚本执行过程中产生的日志记录下来。Python官方提供的日志模块logging
已经非常好用。具体使用方法官方文档有详细介绍:Logging HOWTO — Python 3.9.6 documentation
但是每次记录日志之前,都输入以下类似的代码来配置logging,也是很麻烦的事情。
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
所以我们需要将日志的配置文件放在一个地方,记日志时只需加载配置即可。
编写配置文件
首先用json格式编写一个配置文件,以下是配置文件的模板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": {
"my_module": {
"level": "ERROR",
"handlers": ["console"],
"propagate": false
}
},
"root": {
"level": "INFO",
"handlers": ["console", "info_file_handler", "error_file_handler"]
}
}
编写加载日志配置的模块
在脚本的目录中添加几个加载日志的模块LogSetup.py
,并加以下的函数加入该文件:
|-- LogSetup.py
|-- logging.json
|-- file1.py
|-- file2.py
|-- folder1
|-- file3.py
|-- file4.py
def setup_logging(default_path='logging.json', default_level=logging.DEBUG, env_key='LOG_CFG'):
"""Setup logging configuration"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
加载日志配置并记日志
在脚本文件(file1.py
)中加载日志配置并记录日志:
import logging
import LogSetup
LogSetup.setup_logging()
logger = logging.getLogger(__name__)
logger.debug("Debug log")
logger.info("Info log")
logger.error("Error log")