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

作者:mdxy-dxy 时间:2023-07-06 20:04:30 

前言

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

分析

项目使用了 logging 的 TimedRotatingFileHandler :


#!/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

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


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


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,不删除
0
投稿

猜你喜欢

  • pycharm修改file type方式

    2022-10-08 15:25:36
  • 面试被问select......for update会锁表还是锁行

    2024-01-17 20:59:17
  • 网页特效文字之—银箔字

    2013-08-07 00:21:39
  • python 实现人和电脑猜拳的示例代码

    2021-04-11 01:42:14
  • asp.net mvc 从数据库中读取图片的实现代码

    2024-01-19 14:51:09
  • python将unicode转为str的方法

    2022-04-30 23:15:18
  • 将数据插入到MySQL表中的详细教程

    2024-01-12 22:01:21
  • mysql查找删除重复数据并只保留一条实例详解

    2024-06-05 09:52:53
  • oracle 树查询 语句

    2009-07-17 18:20:00
  • Python基础Lists和tuple实例详解

    2021-09-27 04:11:36
  • 基于Python制作公交车站查询系统

    2022-10-03 04:34:03
  • 使用SpringBoot + Redis 实现接口限流的方式

    2023-07-11 00:06:49
  • python数据结构链表之单向链表(实例讲解)

    2021-01-17 12:51:19
  • pandas处理csv文件的方法步骤

    2022-05-31 10:51:04
  • python+opencv实现的简单人脸识别代码示例

    2021-06-15 01:02:27
  • MySQL 如何查询当前最新事务ID

    2024-01-28 17:23:42
  • javascript中typeof操作符和constucor属性检测

    2024-05-09 10:37:27
  • MySQL版本低了不支持两个时间戳类型的值解决方法

    2024-01-18 14:13:21
  • mysql建表常用sql语句个人经验分享

    2024-01-27 12:30:48
  • python基础之while循环语句的使用

    2021-03-16 16:54:20
  • asp之家 网络编程 m.aspxhome.com