背景
生产环境中整个项目的日志信息需要每一天保存一个日志文件,日志保留的最大时间为30天。
自定义一个日志模块,代码如下:
import os, logging
from datetime import datetime
from logging import handlersclass Logger:"""定义Logger类,日志模块"""level_relations = {"debug": logging.DEBUG,"info": logging.INFO,"warning": logging.WARNING,"error": logging.ERROR,"crit": logging.CRITICAL,}log_dir = "/data/log"if not os.path.exists(log_dir):os.makedirs(log_dir, exist_ok=True)filepath = os.path.join(log_dir, f"xxx_business_logs_{datetime.now().strftime('%Y-%m-%d')}.log")def __init__(self, filename=filepath, level="info", when="D", backCount=7, fmt=None):# 日志保存或打印的格式if fmt is None:fmt = "%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"self.logger = logging.getLogger(filename)if not self.logger.hasHandlers():format_str = logging.Formatter(fmt)self.logger.setLevel(self.level_relations.get(level))# 向控制台或终端输出sh = logging.StreamHandler()sh.setFormatter(format_str)# 以天为单位保存日志文件th = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount, encoding="utf-8")th.setFormatter(format_str)self.logger.addHandler(sh)self.logger.addHandler(th)# 获取日志对象def get_log(self):return self.logger# 整个项目只需要打印一个日志文件,只需要在使用的文件中导入log,
# 调用log = log.get_log()即可使用
log = Logger()