python logging 日志轮转文件不删除问题的解决方法
Python  /  管理员 发布于 7年前   399
前言
最近在维护项目的python项目代码,项目使用了 python 的日志模块 logging, 设定了保存的日志数目, 不过没有生效,还要通过contab定时清理数据。
分析
项目使用了 logging 的 TimedRotatingFileHandler :
#!/user/bin/env python# -*- coding: utf-8 -*-import loggingfrom logging.handlers import TimedRotatingFileHandlerlog = logging.getLogger()file_name = "./test.log"logformatter = logging.Formatter('%(asctime)s [%(levelname)s]|%(message)s')loghandle = TimedRotatingFileHandler(file_name, 'midnight', 1, 2)loghandle.setFormatter(logformatter)loghandle.suffix = '%Y%m%d'log.addHandler(loghandle)log.setLevel(logging.DEBUG)log.debug("init successful")参考 python logging 的官方文档:
https://docs.python.org/2/library/logging.html
查看其 入门 实例,可以看到使用按时间轮转的相关内容:
import logging# create loggerlogger = logging.getLogger('simple_example')logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()ch.setLevel(logging.DEBUG)# create formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# add formatter to chch.setFormatter(formatter)# add ch to loggerlogger.addHandler(ch)# 'application' codelogger.debug('debug message')粗看下,也看不出有什么不对的地方。
那就看下logging的代码,找到TimedRotatingFileHandler 相关的内容,其中删除过期日志的内容:
logging/handlers.py
def getFilesToDelete(self): """ Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob(). """ dirName, baseName = os.path.split(self.baseFilename) fileNames = os.listdir(dirName) result = [] prefix = baseName + "." plen = len(prefix) for fileName in fileNames: if fileName[:plen] == prefix: suffix = fileName[plen:] if self.extMatch.match(suffix): result.append(os.path.join(dirName, fileName)) result.sort() if len(result) < self.backupCount: result = [] else: result = result[:len(result) - self.backupCount] return result
轮转删除的原理,是查找到日志目录下,匹配suffix后缀的文件,加入到删除列表,如果超过了指定的数目就加入到要删除的列表中,再看下匹配的原理:
elif self.when == 'D' or self.when == 'MIDNIGHT': self.interval = 60 * 60 * 24 # one day self.suffix = "%Y-%m-%d" self.extMatch = r"^\d{4}-\d{2}-\d{2}$"exMatch 是一个正则的匹配,格式是 - 分隔的时间,而我们自己设置了新的suffix没有 - 分隔:
loghandle.suffix = '%Y%m%d'
这样就找不到要删除的文件,不会删除相关的日志。
总结
1. 封装好的库,尽量使用公开的接口,不要随便修改内部变量;
2. 代码有问题地,实在找不到原因,可以看下代码。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号
