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.

_file.py 2.4KB

5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # -*- test-case-name: twisted.logger.test.test_file -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. File log observer.
  6. """
  7. from zope.interface import implementer
  8. from twisted.python.compat import ioType, unicode
  9. from ._observer import ILogObserver
  10. from ._format import formatTime
  11. from ._format import timeFormatRFC3339
  12. from ._format import formatEventAsClassicLogText
  13. @implementer(ILogObserver)
  14. class FileLogObserver(object):
  15. """
  16. Log observer that writes to a file-like object.
  17. """
  18. def __init__(self, outFile, formatEvent):
  19. """
  20. @param outFile: A file-like object. Ideally one should be passed which
  21. accepts L{unicode} data. Otherwise, UTF-8 L{bytes} will be used.
  22. @type outFile: L{io.IOBase}
  23. @param formatEvent: A callable that formats an event.
  24. @type formatEvent: L{callable} that takes an C{event} argument and
  25. returns a formatted event as L{unicode}.
  26. """
  27. if ioType(outFile) is not unicode:
  28. self._encoding = "utf-8"
  29. else:
  30. self._encoding = None
  31. self._outFile = outFile
  32. self.formatEvent = formatEvent
  33. def __call__(self, event):
  34. """
  35. Write event to file.
  36. @param event: An event.
  37. @type event: L{dict}
  38. """
  39. text = self.formatEvent(event)
  40. if text is None:
  41. text = u""
  42. if self._encoding is not None:
  43. text = text.encode(self._encoding)
  44. if text:
  45. self._outFile.write(text)
  46. self._outFile.flush()
  47. def textFileLogObserver(outFile, timeFormat=timeFormatRFC3339):
  48. """
  49. Create a L{FileLogObserver} that emits text to a specified (writable)
  50. file-like object.
  51. @param outFile: A file-like object. Ideally one should be passed which
  52. accepts L{unicode} data. Otherwise, UTF-8 L{bytes} will be used.
  53. @type outFile: L{io.IOBase}
  54. @param timeFormat: The format to use when adding timestamp prefixes to
  55. logged events. If L{None}, or for events with no C{"log_timestamp"}
  56. key, the default timestamp prefix of C{u"-"} is used.
  57. @type timeFormat: L{unicode} or L{None}
  58. @return: A file log observer.
  59. @rtype: L{FileLogObserver}
  60. """
  61. def formatEvent(event):
  62. return formatEventAsClassicLogText(
  63. event, formatTime=lambda e: formatTime(e, timeFormat)
  64. )
  65. return FileLogObserver(outFile, formatEvent)