我想创建一个基于时间的BufferingHandler
。当前,BufferingHandler
是基于capacity
的,这意味着只有在达到source code时,它才会刷新记录{{3}}:
capacity
我尝试过的是:
class BufferingHandler(logging.Handler):
def __init__(self, capacity):
logging.Handler.__init__(self)
self.capacity = capacity
self.buffer = []
def shouldFlush(self, record):
return (len(self.buffer) >= self.capacity)
def emit(self, record):
self.buffer.append(record)
if self.shouldFlush(record):
self.flush()
def flush(self):
self.acquire()
try:
self.buffer = []
finally:
self.release()
...
我的class TimeBasedBufferingHandler(BufferingHandler):
def __init__(self, capacity=10, delta=60):
BufferingHandler.__init__(self)
self.capacity = capacity
self.delta = delta # in seconds (as time.time())
def shouldFlush(self, record):
is_full = len(self.buffer) >= self.capacity
is_old = (record.created - self.buffer[0].created) >= self.delta
return is_full or is_old
中的问题是,如果在最后一条记录之后未收到任何记录,并且TimeBasedBufferingHandler
未返回shouldFlush
,则某些日志将被长时间捕获。缓冲区,这不是我想要的。我仍然想在一段时间后释放日志(例如True
),即使未收到触发delta
函数的记录也是如此。
我该怎么做?
答案 0 :(得分:1)
当您要刷新处理程序的缓冲区时,可以从任意位置手动调用flush
。您可以在计时器上执行此操作,例如:
timeout = 60
handler = TimeBasedBufferingHandler(capacity=XXX, delta=timeout)
timer = threading.Timer(timeout, handler.flush)