A logging handler that stores log records and the log text.
| 386 | |
| 387 | |
| 388 | class LogCaptureHandler(logging_StreamHandler): |
| 389 | """A logging handler that stores log records and the log text.""" |
| 390 | |
| 391 | def __init__(self) -> None: |
| 392 | """Create a new log handler.""" |
| 393 | super().__init__(StringIO()) |
| 394 | self.records: list[logging.LogRecord] = [] |
| 395 | |
| 396 | def emit(self, record: logging.LogRecord) -> None: |
| 397 | """Keep the log records in a list in addition to the log text.""" |
| 398 | self.records.append(record) |
| 399 | super().emit(record) |
| 400 | |
| 401 | def reset(self) -> None: |
| 402 | self.records = [] |
| 403 | self.stream = StringIO() |
| 404 | |
| 405 | def clear(self) -> None: |
| 406 | self.records.clear() |
| 407 | self.stream = StringIO() |
| 408 | |
| 409 | def handleError(self, record: logging.LogRecord) -> None: |
| 410 | if logging.raiseExceptions: |
| 411 | # Fail the test if the log message is bad (emit failed). |
| 412 | # The default behavior of logging is to print "Logging error" |
| 413 | # to stderr with the call stack and some extra details. |
| 414 | # pytest wants to make such mistakes visible during testing. |
| 415 | raise # noqa: PLE0704 |
| 416 | |
| 417 | |
| 418 | @final |
no outgoing calls