2021-01-22 Python TimedRotatingFileHandler 修改suffix后无法自动删除文件

Python TimedRotatingFileHandler 修改suffix后无法自动删除文件

TimedRotatingFileHandler 用法

“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight

设计1s一个日志,超过3个删除

	log = logging.getLogger()
	log.setLevel(logging.ERROR)  # 日志等级为ERROR
	
	fh = logging.handlers.TimedRotatingFileHandler("log", when='S', interval=1, backupCount=3)
	fh.suffix = "%Y-%m-%d_%H-%M-%S.log"
	formatter = logging.Formatter('[%(asctime)s] - %(filename)s [Line:%(lineno)d] - [%(levelname)s]-[thread:%(thread)s]-[process:%(process)s] - %(message)s') 
	fh.setFormatter(formatter)
	log.addHandler(fh)
	i = 0
	while i < 100000000:
	    sleep(0.1)
	    log.error("记录" + str(i))
	    i = i + 1

结果是并不会删除

2021-01-22 Python TimedRotatingFileHandler 修改suffix后无法自动删除文件

查看TimedRotatingFileHandler的源码

def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False):
        BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)
        self.when = when.upper()
        self.backupCount = backupCount
        self.utc = utc      
        if self.when == 'S':
            self.interval = 1 # one second
            self.suffix = "%Y-%m-%d_%H-%M-%S"
            self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$"
        elif self.when == 'M':
            self.interval = 60 # one minute
            self.suffix = "%Y-%m-%d_%H-%M"
            self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$"
        elif self.when == 'H':
            self.interval = 60 * 60 # one hour
            self.suffix = "%Y-%m-%d_%H"
            self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}$"
        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}$"
        elif self.when.startswith('W'):
            self.interval = 60 * 60 * 24 * 7 # one week
            if len(self.when) != 2:
                raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
            if self.when[1] < '0' or self.when[1] > '6':
                raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
            self.dayOfWeek = int(self.when[1])
            self.suffix = "%Y-%m-%d"
            self.extMatch = r"^\d{4}-\d{2}-\d{2}$"
        else:
            raise ValueError("Invalid rollover interval specified: %s" % self.when)

        self.extMatch = re.compile(self.extMatch)
        self.interval = self.interval * interval # multiply by units requested
        if os.path.exists(filename):
            t = os.stat(filename)[ST_MTIME]
        else:
            t = int(time.time())
        self.rolloverAt = self.computeRollover(t)

关键是下面的几行

self.suffix = "%Y-%m-%d_%H-%M-%S"
self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$"
······
······
self.extMatch = re.compile(self.extMatch)

默认设置when类型后,suffix是固定的,匹配的正则也是源码里写好的,所以当修改suffix后,必须连带正则一并修改

最终代码如下

log = logging.getLogger()
log.setLevel(logging.ERROR)  # 日志等级为ERROR

fh = logging.handlers.TimedRotatingFileHandler("log", when='S', interval=1, backupCount=3)
fh.suffix = "%Y-%m-%d_%H-%M-%S.log"
fh.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}.log$"
fh.extMatch = re.compile(fh.extMatch)
formatter = logging.Formatter('[%(asctime)s] - %(filename)s [Line:%(lineno)d] - [%(levelname)s]-[thread:%(thread)s]-[process:%(process)s] - %(message)s') 
fh.setFormatter(formatter)
log.addHandler(fh)
i = 0
while i < 100000000:
    sleep(0.1)
    log.error("记录" + str(i))
    i = i + 1

2021-01-22 Python TimedRotatingFileHandler 修改suffix后无法自动删除文件

 

 

 

上一篇:24点 python 待优化


下一篇:判断该文件是否是Excel文档