python logging 日志輪轉(zhuǎn)文件不刪除問題的解決方法
前言
最近在維護(hù)項(xiàng)目的python項(xiàng)目代碼,項(xiàng)目使用了 python 的日志模塊 logging, 設(shè)定了保存的日志數(shù)目, 不過沒有生效,還要通過contab定時(shí)清理數(shù)據(jù)。
分析
項(xiàng)目使用了 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
查看其 入門 實(shí)例,可以看到使用按時(shí)間輪轉(zhuǎn)的相關(guān)內(nèi)容:
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')
粗看下,也看不出有什么不對(duì)的地方。
那就看下logging的代碼,找到TimedRotatingFileHandler 相關(guān)的內(nèi)容,其中刪除過期日志的內(nèi)容:
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
輪轉(zhuǎn)刪除的原理,是查找到日志目錄下,匹配suffix后綴的文件,加入到刪除列表,如果超過了指定的數(shù)目就加入到要?jiǎng)h除的列表中,再看下匹配的原理:
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 是一個(gè)正則的匹配,格式是 - 分隔的時(shí)間,而我們自己設(shè)置了新的suffix沒有 - 分隔:
loghandle.suffix = '%Y%m%d'
這樣就找不到要?jiǎng)h除的文件,不會(huì)刪除相關(guān)的日志。
總結(jié)
1. 封裝好的庫,盡量使用公開的接口,不要隨便修改內(nèi)部變量;
2. 代碼有問題地,實(shí)在找不到原因,可以看下代碼。
- python標(biāo)準(zhǔn)日志模塊logging的使用方法
- Python中內(nèi)置的日志模塊logging用法詳解
- Python中使用logging模塊打印log日志詳解
- Python中使用logging模塊代替print(logging簡明指南)
- Python同時(shí)向控制臺(tái)和文件輸出日志logging的方法
- python改變?nèi)罩?logging)存放位置的示例
- python中使用sys模板和logging模塊獲取行號(hào)和函數(shù)名的方法
- python中 logging的使用詳解
- Python使用logging模塊實(shí)現(xiàn)打印log到指定文件的方法
- python 通過logging寫入日志到文件和控制臺(tái)的實(shí)例
- 詳解Python中的日志模塊logging
- python logging類庫使用例子
- 詳解Python logging調(diào)用Logger.info方法的處理過程
- 解決Python中由于logging模塊誤用導(dǎo)致的內(nèi)存泄露
- 說一說Python logging
- Python中l(wèi)ogging模塊的用法實(shí)例
- Python logging模塊學(xué)習(xí)筆記
- 多個(gè)python文件調(diào)用logging模塊報(bào)錯(cuò)誤
相關(guān)文章
jupyter?notebook?自定義python解釋器的過程詳解
大家都知道jupyter?notebook?網(wǎng)頁版交互環(huán)境,類似于ipython,功能強(qiáng)大,這篇文章主要介紹了jupyter?notebook?自定義python解釋器的過程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-10-10
Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)多輸入多輸出通道
這篇文章主要為大家介紹了Python深度學(xué)習(xí)中pytorch神經(jīng)網(wǎng)絡(luò)多輸入多輸出通道的詳解有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-10-10
Python實(shí)現(xiàn)中文文本關(guān)鍵詞抽取的三種方法
文本關(guān)鍵詞抽取,是對(duì)文本信息進(jìn)行高度凝練的一種有效手段,通過3-5個(gè)詞語準(zhǔn)確概括文本的主題,幫助讀者快速理解文本信息,本文分別采用TF-IDF方法、TextRank方法和Word2Vec詞聚類方法,利用Python語言進(jìn)行開發(fā),實(shí)現(xiàn)文本關(guān)鍵詞的抽取,需要的朋友可以參考下2024-01-01
Python numpy生成矩陣、串聯(lián)矩陣代碼分享
這篇文章主要介紹了Python numpy生成矩陣、串聯(lián)矩陣代碼分享,具有一定參考價(jià)值,需要的朋友可以了解下。2017-12-12

