我对日志记录有些困惑。我希望在一定时间后和达到一定大小后滚动日志。
使用TimedRotatingFileHandler
可以在一定时间后滚动日志,
而使用RotatingFileHandler
可以在达到一定日志大小后滚动日志。
但是TimedRotatingFileHandler
没有maxBytes
属性,RotatingFileHandler
不能在一定时间后滚动日志。
我尝试将两个处理程序添加到记录器中,但结果是日志记录翻倍。
我错过了什么吗?
我还查看了logging.handlers
的源代码。我尝试子类化TimedRotatingFileHandler
并覆盖shouldRollover()
方法,以创建具有双重功能的类:
class EnhancedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0, utc=0, maxBytes=0):
""" This is just a combination of TimedRotatingFileHandler and RotatingFileHandler (adds maxBytes to TimedRotatingFileHandler) """
# super(self). #It's old style class, so super doesn't work.
logging.handlers.TimedRotatingFileHandler.__init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0, utc=0)
self.maxBytes=maxBytes
def shouldRollover(self, record):
"""
Determine if rollover should occur.
Basically, see if the supplied record would cause the file to exceed
the size limit we have.
we are also comparing times
"""
if self.stream is None: # delay was set...
self.stream = self._open()
if self.maxBytes > 0: # are we rolling over?
msg = "%s\n" % self.format(record)
self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
if self.stream.tell() + len(msg) >= self.maxBytes:
return 1
t = int(time.time())
if t >= self.rolloverAt:
return 1
#print "No need to rollover: %d, %d" % (t, self.rolloverAt)
return 0
但是这样日志会创建一个备份并被覆盖。似乎我也必须覆盖doRollover()
方法,这不太容易。
还有其他的想法如何创建一个在一定时间后滚动文件并在达到一定大小后滚动文件的日志记录器吗?