You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_buffer.py 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # -*- test-case-name: twisted.logger.test.test_buffer -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Log observer that maintains a buffer.
  6. """
  7. from collections import deque
  8. from zope.interface import implementer
  9. from ._observer import ILogObserver
  10. _DEFAULT_BUFFER_MAXIMUM = 64 * 1024
  11. @implementer(ILogObserver)
  12. class LimitedHistoryLogObserver(object):
  13. """
  14. L{ILogObserver} that stores events in a buffer of a fixed size::
  15. >>> from twisted.logger import LimitedHistoryLogObserver
  16. >>> history = LimitedHistoryLogObserver(5)
  17. >>> for n in range(10): history({'n': n})
  18. ...
  19. >>> repeats = []
  20. >>> history.replayTo(repeats.append)
  21. >>> len(repeats)
  22. 5
  23. >>> repeats
  24. [{'n': 5}, {'n': 6}, {'n': 7}, {'n': 8}, {'n': 9}]
  25. >>>
  26. """
  27. def __init__(self, size=_DEFAULT_BUFFER_MAXIMUM):
  28. """
  29. @param size: The maximum number of events to buffer. If L{None}, the
  30. buffer is unbounded.
  31. @type size: L{int}
  32. """
  33. self._buffer = deque(maxlen=size)
  34. def __call__(self, event):
  35. self._buffer.append(event)
  36. def replayTo(self, otherObserver):
  37. """
  38. Re-play the buffered events to another log observer.
  39. @param otherObserver: An observer to replay events to.
  40. @type otherObserver: L{ILogObserver}
  41. """
  42. for event in self._buffer:
  43. otherObserver(event)