A logging handler that stores log records and the log text.
| 323 | |
| 324 | |
| 325 | class LogCaptureHandler(logging.StreamHandler): |
| 326 | """A logging handler that stores log records and the log text.""" |
| 327 | |
| 328 | stream: StringIO |
| 329 | |
| 330 | def __init__(self) -> None: |
| 331 | """Create a new log handler.""" |
| 332 | super().__init__(StringIO()) |
| 333 | self.records: List[logging.LogRecord] = [] |
| 334 | |
| 335 | def emit(self, record: logging.LogRecord) -> None: |
| 336 | """Keep the log records in a list in addition to the log text.""" |
| 337 | self.records.append(record) |
| 338 | super().emit(record) |
| 339 | |
| 340 | def reset(self) -> None: |
| 341 | self.records = [] |
| 342 | self.stream = StringIO() |
| 343 | |
| 344 | def handleError(self, record: logging.LogRecord) -> None: |
| 345 | if logging.raiseExceptions: |
| 346 | # Fail the test if the log message is bad (emit failed). |
| 347 | # The default behavior of logging is to print "Logging error" |
| 348 | # to stderr with the call stack and some extra details. |
| 349 | # pytest wants to make such mistakes visible during testing. |
| 350 | raise |
| 351 | |
| 352 | |
| 353 | @final |