-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
29 additions
and
33 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
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
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 |
---|---|---|
@@ -1,25 +1,27 @@ | ||
|
||
import logging | ||
from typing import List, Tuple, Iterable | ||
|
||
|
||
LoggerName = str | ||
_structured_logs: List[Tuple[LoggerName, logging.LogRecord]] = [] | ||
from typing import List, Tuple, Iterable, Callable | ||
|
||
|
||
class InMemoryLogHandler(logging.Handler): | ||
def __init__(self, name: str, *args, **kwargs) -> None: | ||
super().__init__(*args, **kwargs) | ||
self.name: str = name | ||
self.logs: List[logging.LogRecord] = [] | ||
self.callbacks = [] | ||
|
||
|
||
def emit(self, record: logging.LogRecord): | ||
_structured_logs.append((self.name, record)) | ||
self.logs.append(record) | ||
for callback in self.callbacks: | ||
callback(record) | ||
|
||
|
||
def register_structured_logger(logger: logging.Logger): | ||
memory_handler = InMemoryLogHandler(logger.name) | ||
logger.addHandler(memory_handler) | ||
def addCallback(self, callback: Callable[[logging.LogRecord], object]): | ||
self.callbacks.append(callback) | ||
|
||
|
||
def iterate_messages() -> Iterable[Tuple[LoggerName, logging.LogRecord]]: | ||
yield from _structured_logs | ||
def add_structured_handler(logger: logging.Logger): | ||
memory_handler = InMemoryLogHandler(logger.name) | ||
logger.addHandler(memory_handler) | ||
return memory_handler |