python logging 日誌輪轉文件不刪除問題

前言

最近在維護項目的python項目代碼,項目使用了 python 的日誌模塊 logging, 設定了保存的日誌數目, 不過沒有生效,還要經過contab定時清理數據。html

分析

項目使用了 logging 的 TimedRotatingFileHandler :python

 1 #!/user/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 import logging
 5 from logging.handlers import TimedRotatingFileHandler
 6 log = logging.getLogger()
 7 file_name = "./test.log"
 8 logformatter = logging.Formatter('%(asctime)s [%(levelname)s]|%(message)s')
 9 loghandle = TimedRotatingFileHandler(file_name, 'midnight', 1, 2)
10 loghandle.setFormatter(logformatter)
11 loghandle.suffix = '%Y%m%d'
12 log.addHandler(loghandle)
13 log.setLevel(logging.DEBUG)
14 
15 log.debug("init successful")

參考 python logging 的官方文檔:app

https://docs.python.org/2/library/logging.htmlspa

查看其 入門 實例,能夠看到使用按時間輪轉的相關內容:debug

 1 import logging
 2 
 3 # create logger
 4 logger = logging.getLogger('simple_example')
 5 logger.setLevel(logging.DEBUG)
 6 
 7 # create console handler and set level to debug
 8 ch = logging.StreamHandler()
 9 ch.setLevel(logging.DEBUG)
10 
11 # create formatter
12 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
13 
14 # add formatter to ch
15 ch.setFormatter(formatter)
16 
17 # add ch to logger
18 logger.addHandler(ch)
19 
20 # 'application' code
21 logger.debug('debug message')

粗看下,也看不出有什麼不對的地方。日誌

那就看下logging的代碼,找到TimedRotatingFileHandler 相關的內容,其中刪除過時日誌的內容:code

logging/handlers.pyorm

    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後綴的文件,加入到刪除列表,若是超過了指定的數目就加入到要刪除的列表中,再看下匹配的原理:htm

        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沒有 - 分隔:blog

loghandle.suffix = '%Y%m%d'

這樣就找不到要刪除的文件,不會刪除相關的日誌。

總結

1. 封裝好的庫,儘可能使用公開的接口,不要隨便修改內部變量; 

2. 代碼有問題地,實在找不到緣由,能夠看下代碼。

相關文章
相關標籤/搜索