python logging 日志輪轉(zhuǎn)文件不刪除問題的解決方法
前言
最近在維護項目的python項目代碼,項目使用了 python 的日志模塊 logging, 設(shè)定了保存的日志數(shù)目, 不過沒有生效,還要通過contab定時清理數(shù)據(jù)。
分析
項目使用了 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
查看其 入門 實例,可以看到使用按時間輪轉(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')
粗看下,也看不出有什么不對的地方。
那就看下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ù)目就加入到要刪除的列表中,再看下匹配的原理:
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 是一個正則的匹配,格式是 - 分隔的時間,而我們自己設(shè)置了新的suffix沒有 - 分隔:
loghandle.suffix = '%Y%m%d'
這樣就找不到要刪除的文件,不會刪除相關(guān)的日志。
總結(jié)
1. 封裝好的庫,盡量使用公開的接口,不要隨便修改內(nèi)部變量;
2. 代碼有問題地,實在找不到原因,可以看下代碼。
- python標準日志模塊logging的使用方法
- Python中內(nèi)置的日志模塊logging用法詳解
- Python中使用logging模塊打印log日志詳解
- Python中使用logging模塊代替print(logging簡明指南)
- Python同時向控制臺和文件輸出日志logging的方法
- python改變?nèi)罩?logging)存放位置的示例
- python中使用sys模板和logging模塊獲取行號和函數(shù)名的方法
- python中 logging的使用詳解
- Python使用logging模塊實現(xiàn)打印log到指定文件的方法
- python 通過logging寫入日志到文件和控制臺的實例
- 詳解Python中的日志模塊logging
- python logging類庫使用例子
- 詳解Python logging調(diào)用Logger.info方法的處理過程
- 解決Python中由于logging模塊誤用導(dǎo)致的內(nèi)存泄露
- 說一說Python logging
- Python中l(wèi)ogging模塊的用法實例
- Python logging模塊學(xué)習(xí)筆記
- 多個python文件調(diào)用logging模塊報錯誤
相關(guān)文章
Python計算標準差之numpy.std和torch.std的區(qū)別
Torch自稱為神經(jīng)網(wǎng)絡(luò)中的numpy,它會將torch產(chǎn)生的tensor放在GPU中加速運算,就像numpy會把array放在CPU中加速運算,下面這篇文章主要給大家介紹了關(guān)于Python?Numpy計算標準差之numpy.std和torch.std區(qū)別的相關(guān)資料,需要的朋友可以參考下2022-08-08Python爬取網(wǎng)站圖片并保存的實現(xiàn)示例
這篇文章主要介紹了Python爬取網(wǎng)站圖片并保存的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02淺析Python+OpenCV使用攝像頭追蹤人臉面部血液變化實現(xiàn)脈搏評估
這篇文章主要介紹了Python+OpenCV使用攝像頭追蹤人臉面部血液變化實現(xiàn)脈搏評估,本文通過一段代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10