python logging 日志轮转文件不删除问题的解决方法

python logging 日志轮转文件不删除问题的解决方法,第1张

概述前言最近在维护项目的python项目代码,项目使用了python的日志模块logging,设定了保存的日志数目,不过没有生效,还要通过contab定时清理数据。

前言

最近在维护项目的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. 代码有问题地,实在找不到原因,可以看下代码。

总结

以上是内存溢出为你收集整理的python logging 日志轮转文件不删除问题的解决方法全部内容,希望文章能够帮你解决python logging 日志轮转文件不删除问题的解决方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1203762.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存