This repository has been archived by the owner on Apr 26, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add PeriodicallyFlushingMemoryHandler
- Loading branch information
1 parent
6a60068
commit 65a3755
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import logging | ||
import time | ||
from logging import Handler | ||
from logging.handlers import MemoryHandler | ||
from threading import Thread | ||
from typing import Optional | ||
|
||
|
||
class PeriodicallyFlushingMemoryHandler(MemoryHandler): | ||
""" | ||
This is a subclass of MemoryHandler which additionally spawns a background | ||
thread which periodically flushes the buffers. | ||
This prevents messages from being buffered for too long. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
capacity: int, | ||
flushLevel: int = logging.ERROR, | ||
target: Optional[Handler] = None, | ||
flushOnClose: bool = True, | ||
period: float = 5.0, | ||
) -> None: | ||
super().__init__(capacity, flushLevel, target, flushOnClose) | ||
|
||
self._flush_period: float = period | ||
self._active: bool = True | ||
|
||
self._flushing_thread: Thread = Thread( | ||
name="PeriodicallyFlushingMemoryHandler flushing thread", | ||
target=self._flush_periodically, | ||
) | ||
self._flushing_thread.start() | ||
|
||
def _flush_periodically(self): | ||
while self._active: | ||
self.flush() | ||
time.sleep(self._flush_period) | ||
|
||
def close(self) -> None: | ||
self._active = False | ||
super().close() |