_capture.py 624 B

12345678910111213141516171819202122232425
  1. # -*- test-case-name: twisted.logger.test.test_capture -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Context manager for capturing logs.
  6. """
  7. from contextlib import contextmanager
  8. from typing import Iterator, List, Sequence, cast
  9. from twisted.logger import globalLogPublisher
  10. from ._interfaces import ILogObserver, LogEvent
  11. @contextmanager
  12. def capturedLogs() -> Iterator[Sequence[LogEvent]]:
  13. events: List[LogEvent] = []
  14. observer = cast(ILogObserver, events.append)
  15. globalLogPublisher.addObserver(observer)
  16. yield events
  17. globalLogPublisher.removeObserver(observer)