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

项目使用了 logging 的 TimedRotatingFileHandler :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/user/bin/env python
# -*- coding: utf-8 -*-
 
import logging
from logging.handlers import TimedRotatingFileHandler
log = 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

查看其 入门 实例,可以看到使用按时间轮转的相关内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import logging
 
# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
 
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
 
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 
# add formatter to ch
ch.setFormatter(formatter)
 
# add ch to logger
logger.addHandler(ch)
 
# 'application' code
logger.debug('debug message')

粗看下,也看不出有什么不对的地方。

那就看下logging的代码,找到TimedRotatingFileHandler 相关的内容,其中删除过期日志的内容:

logging/handlers.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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后缀的文件,加入到删除列表,如果超过了指定的数目就加入到要删除的列表中,再看下匹配的原理:

1
2
3
4
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'
这样就找不到要删除的文件,不会删除相关的日志。

posted @   邱明成  阅读(1003)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
历史上的今天:
2019-07-17 xshell怎么配置鼠标颜色
2016-07-17 win7 vi工具
2016-07-17 开源java数据库库
2016-07-17 win7快捷键
点击右上角即可分享
微信分享提示