python logging 日志轮转文件不删除问题
前言
最近在维护项目的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 日志轮转文件不删除问题的更多相关文章
- python logging 日志轮转文件不删除问题的解决方法
项目使用了 logging 的 TimedRotatingFileHandler : #!/user/bin/env python # -*- coding: utf-8 -*- import log ...
- Python logging(日志)模块
python日志模块 内容简介 1.日志相关概念 2.logging模块简介 3.logging模块函数使用 4.logging模块日志流处理流程 5.logging模块组件使用 6.logging配 ...
- Python logging日志系统
写我小小的日志系统 配置logging有以下几种方式: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数: 2)创建一个日志配置文件, ...
- python logging日志输出个文件中
# -*- coding:utf-8 -*- import logging # 引入logging模块 import os.path import time # 第一步,创建一个logger logg ...
- python logging日志模块
一.logging模块的简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不 ...
- 管理 python logging 日志使用
1.日志级别 日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICAL. DEBUG:详细的信息,通常只出现在诊断问题上INFO:确认一切按预期运行WA ...
- python logging 日志
logging与print 区别,为什么需要logging? 在写脚本的过程中,为了调试程序,我们往往会写很多print打印输出以便用于验证,验证正确后往往会注释掉,一旦验证的地方比较多,再一一注释比 ...
- python logging 日志使用
https://docs.python.org/3/library/logging.html1.日志级别 日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRI ...
- Python logging日志管理
import logging logger = logging.getLogger("simple_example") logger.setLevel(logging.DEBUG) ...
随机推荐
- webservice简单总结
一:webservice定义 webservice是一种基于xml,xsd封装格式,通过http协议通信的一种服务,支持跨平台.跨语言的 远程调用. 二:webservice优点 1:跨平台,无论是w ...
- poj 2724 二分图最大匹配
题意: 会给出M个串,我们要做的就是将这M个串给清除了.对于任意两个串,若二进制形式只有一位不一样,那么这两个串可以在一次操作消除,否则每个操作只能消除一个串. 3 3 *01 100 011 可以代 ...
- poj2243
Knight Moves Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 13433 Accepted: 7518 Des ...
- Jersey(1.19.1) - Client API, Overview of the API
To utilize the client API it is first necessary to create an instance of a Client, for example: Clie ...
- MyBatis(3.2.3) - hello world
1. 创建数据表(MySQL): DROP TABLE IF EXISTS `department`; CREATE TABLE `department` ( `did` ) unsigned NOT ...
- Git CMD - init: Create an empty Git repository or reinitialize an existing one
命令格式 git init [-q | --quiet] [--bare] [--template=<template_directory>] [--separate-git-dir &l ...
- JAVA鼠标屏幕绘制拖拽删除矩形
import java.awt.Cursor; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; ...
- Java之日期和时间的计算
学习是一个循序渐进的过程,不知道你们有没有这样的感受:有很多学习过的知识在很久没有温习之后就不知不觉地还给老师了.所以最近总结,把那些还给老师的再找回来. 运行图: 时间戳: 运行效果图: 时间日期的 ...
- 2013年7月28日web前端学习笔记-------head相关标签应用
7月份快过完了.趁周日写写学过觉得有用的东西. 1.缩略图的展示问题,不要以为缩略图设置了width,height,就是缩略图了.比如一个300kb的500*500原始图片,用户请求web服务器后,展 ...
- compress 表设置及索引设置
-- 查看表大小 from user_segments where segment_name='TableName'; -- 查看表大小 size_m -- 2000.6796875 2211.695 ...