目的
logging.handlers模块自带的文件分割只支持一下两种模式:
RotatingFileHandler 类位于 logging.handlers 模块,它支持磁盘日志文件的轮换。
TimedRotatingFileHandler 类位于 logging.handlers 模块,它支持基于特定时间间隔的磁盘日志文件轮换。
详见python官方文档
有些时候我们需要按时间分割,但是如果日志过多,还是存在文件过大的情况,这个时候就需要在时间的维度上再根据文件大小进行分割,所以就有了按时间+文件大小的维度分割文件的想法。
具体如下:
代码
#test5.py
from logging.handlers import TimedRotatingFileHandler
import os
import time
_MIDNIGHT = 24 * 60 * 60
class TimedSizeRotatingFileHandler(TimedRotatingFileHandler):
"""
拓展TimedRotatingFileHandler,按时间和文件大小分割
"""
def __init__(self, filename, maxBytes=0, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None):
TimedRotatingFileHandler.__init__(
self, filename, when, interval, backupCount, encoding, delay, utc, atTime)
self.maxBytes = maxBytes
self.count = 0
def shouldRollover(self, record):
t = int(time.time())
if t >= self.rolloverAt:
return 1
# 文件够大时roll,搬运自RotatingFileHandler
if self.stream is None:
self.stream = self._open()
if self.maxBytes > 0:
msg = "%s\n" % self.format(record)
self.stream.seek(0, 2)
if self.stream.tell() + len(msg) >= self.maxBytes:
return 1
return 0
def doRollover(self):
"""
do a rollover; in this case, a date/time stamp is appended to the filename
when the rollover happens. However, you want the file to be named for the
start of the interval, not the current time. If there is a backup count,
then we have to get a list of matching filenames, sort them and remove
the one with the oldest suffix