python 日志 按日期或大小归档
随着回调的事件与越来越多,如果每个事件都写一个方法,这就显得代码的冗余,所以,今天将日志都归档,分类
事件日志,看情况,我们一般保留10天,至于错误日志,一般不会报错,所以我们按文件的大小进行分类
# 按日期进行分类 import logging import logging.handlers as handlers class InfoLog(object): def __init__(self, file_name): formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.logHandler = handlers.TimedRotatingFileHandler(file_name, when='D', interval=1, backupCount=10) self.logHandler.setLevel(logging.INFO) self.logHandler.setFormatter(formatter) self.file_name = file_name self.cons = logging.basicConfig(format='%(asctime)s: %(message)s', level=logging.INFO) def send_msg(self, msg): logger = logging.getLogger(self.file_name) logger.setLevel(logging.INFO) logger.addHandler(self.logHandler) logger.info(msg) callback = InfoLog("callback.log") callback.send_msg("33")
# 按大小进行分类 import logging import logging.handlers as handlers class ErrLog(object): def __init__(self, file_name): formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.errorLogHandler = handlers.RotatingFileHandler(file_name, maxBytes=5000, backupCount=0) self.errorLogHandler.setLevel(logging.INFO) self.errorLogHandler.setFormatter(formatter) self.file_name = file_name self.cons = logging.basicConfig(format='%(asctime)s: %(message)s', level=logging.INFO) def send_msg(self, msg): logger = logging.getLogger(self.file_name) logger.setLevel(logging.INFO) logger.addHandler(self.errorLogHandler) logger.info(msg) err = ErrLog("err.log") err.send_msg("44")
# 对其中出现的参数进行说明 # backupCount 备份的数量 # filename 文件完整路径 # formatter 要使用的日志格式 # level 日志级别 # interval 增量的频率