前言
最近在維護(hù)項(xiàng)目的python項(xiàng)目代碼,項(xiàng)目使用了 python 的日志模塊 logging, 設(shè)定了保存的日志數(shù)目, 不過(guò)沒(méi)有生效,還要通過(guò)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)容,其中刪除過(guò)期日志的內(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后綴的文件,加入到刪除列表,如果超過(guò)了指定的數(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沒(méi)有 - 分隔:
loghandle.suffix = '%Y%m%d'
這樣就找不到要?jiǎng)h除的文件,不會(huì)刪除相關(guān)的日志。
總結(jié)
1. 封裝好的庫(kù),盡量使用公開(kāi)的接口,不要隨便修改內(nèi)部變量;
2. 代碼有問(wèn)題地,實(shí)在找不到原因,可以看下代碼。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

