import logging, os # 引入日期模板 import date # 定义MyLog类 class MyLog(object): # 类MyLog的构造函数 def __init__(self, name): self.name = name self.logger = logging.getLogger(self.name) # 定义日志等级 self.logger.setLevel(logging.DEBUG) # 当前时间 self.day_date = date.now_date('d') # 五天前时间 self.old_date = date.forward_or_back_day(-5, 'd') self.log_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logs/') # 存放日志文件的位置 if not os.path.exists(self.log_path): os.makedirs(self.log_path) self.log_info_name = f'{self.log_path}{self.day_date + "-info.log"}' # 输出到info等级日志文件 self.log_info_file = logging.FileHandler(self.log_info_name, 'a', encoding='utf-8') self.log_error_name = f'{self.log_path}{self.day_date + "-error.log"}' # 输出到error等级日志文件 self.log_error_file = logging.FileHandler(self.log_error_name, 'a', encoding='utf-8') # 删除五天前的日志文件 file_list = [] for cur_path, cur_dirs, cur_files in os.walk(self.log_path): for name in cur_files: file_list.append(os.path.join(cur_path, name)) for file in file_list: if file.endswith('.log'): file_name = os.path.split(file)[1] if self.old_date in file_name: os.remov(file) # 设定输出日志输出格式 self.formatter = logging.Formatter( '%(asctime)s | %(levelname)s | %(name)s | %(filename)s:[%(lineno)d] | %(message)s') self.log_info_file.setFormatter(self.formatter) self.log_info_file.setLevel(logging.DEBUG) self.log_error_file.setFormatter(self.formatter) self.log_error_file.setLevel(logging.DEBUG) # 输出到控制台 self.log_screen = logging.StreamHandler() self.log_screen.setFormatter(self.formatter) self.log_screen.setLevel(logging.DEBUG) # 设置过滤info日志等级过滤条件 info_filter = logging.Filter() info_filter.filter = lambda record: record.levelno == logging.INFO self.log_info_file.addFilter(info_filter) # 设置过滤error日志等级过滤条件 error_filter = logging.Filter() error_filter.filter = lambda record: record.levelno >= logging.WARNING self.log_error_file.addFilter(error_filter) # 输出到文件 self.logger.addHandler(self.log_info_file) self.logger.addHandler(self.log_error_file) # 输出到控制台 self.logger.addHandler(self.log_screen) # 日志的5个级别对应以下的5个函数 def debug(self, msg): """ :param msg:msg对应传入debug等级的日志信息 :return: 返回日志信息 """ self.logger.debug(msg) def info(self, msg): """ :param msg: msg对应传入info等级的日志信息 :return: 返回日志信息 """ self.logger.info(msg) def warning(self, msg): """ :param msg: msg对应传入waring等级的日志信息 :return: 返回日志信息 """ self.logger.warning(msg) def error(self, msg): """ :param msg: msg对应传入error等级的日志信息 :return: 返回日志信息 """ self.logger.error(msg) def critical(self, msg): """ :param msg: msg对应传入citical等级的日志信息 :return: 返回日志信息 """ self.logger.critical(msg)