_global.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. # -*- test-case-name: twisted.logger.test.test_global -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. This module includes process-global state associated with the logging system,
  6. and implementation of logic for managing that global state.
  7. """
  8. import sys
  9. import warnings
  10. from twisted.python.compat import currentframe
  11. from twisted.python.reflect import qual
  12. from ._buffer import LimitedHistoryLogObserver
  13. from ._observer import LogPublisher
  14. from ._filter import FilteringLogObserver, LogLevelFilterPredicate
  15. from ._logger import Logger
  16. from ._format import eventAsText
  17. from ._levels import LogLevel
  18. from ._io import LoggingFile
  19. from ._file import FileLogObserver
  20. MORE_THAN_ONCE_WARNING = (
  21. "Warning: primary log target selected twice at <{fileNow}:{lineNow}> - "
  22. "previously selected at <{fileThen}:{lineThen}>. Remove one of the calls "
  23. "to beginLoggingTo."
  24. )
  25. class LogBeginner(object):
  26. """
  27. A L{LogBeginner} holds state related to logging before logging has begun,
  28. and begins logging when told to do so. Logging "begins" when someone has
  29. selected a set of observers, like, for example, a L{FileLogObserver} that
  30. writes to a file on disk, or to standard output.
  31. Applications will not typically need to instantiate this class, except
  32. those which intend to initialize the global logging system themselves,
  33. which may wish to instantiate this for testing. The global instance for
  34. the current process is exposed as
  35. L{twisted.logger.globalLogBeginner}.
  36. Before logging has begun, a L{LogBeginner} will:
  37. 1. Log any critical messages (e.g.: unhandled exceptions) to the given
  38. file-like object.
  39. 2. Save (a limited number of) log events in a
  40. L{LimitedHistoryLogObserver}.
  41. @ivar _initialBuffer: A buffer of messages logged before logging began.
  42. @type _initialBuffer: L{LimitedHistoryLogObserver}
  43. @ivar _publisher: The log publisher passed in to L{LogBeginner}'s
  44. constructor.
  45. @type _publisher: L{LogPublisher}
  46. @ivar _log: The logger used to log messages about the operation of the
  47. L{LogBeginner} itself.
  48. @type _log: L{Logger}
  49. @ivar _temporaryObserver: If not L{None}, an L{ILogObserver} that observes
  50. events on C{_publisher} for this L{LogBeginner}.
  51. @type _temporaryObserver: L{ILogObserver} or L{None}
  52. @ivar _stdio: An object with C{stderr} and C{stdout} attributes (like the
  53. L{sys} module) which will be replaced when redirecting standard I/O.
  54. @type _stdio: L{object}
  55. @cvar _DEFAULT_BUFFER_SIZE: The default size for the initial log events
  56. buffer.
  57. @type _DEFAULT_BUFFER_SIZE: L{int}
  58. """
  59. _DEFAULT_BUFFER_SIZE = 200
  60. def __init__(
  61. self, publisher, errorStream, stdio, warningsModule,
  62. initialBufferSize=None,
  63. ):
  64. """
  65. Initialize this L{LogBeginner}.
  66. @param initialBufferSize: The size of the event buffer into which
  67. events are collected until C{beginLoggingTo} is called. Or
  68. C{None} to use the default size.
  69. @type initialBufferSize: L{int} or L{types.NoneType}
  70. """
  71. if initialBufferSize is None:
  72. initialBufferSize = self._DEFAULT_BUFFER_SIZE
  73. self._initialBuffer = LimitedHistoryLogObserver(size=initialBufferSize)
  74. self._publisher = publisher
  75. self._log = Logger(observer=publisher)
  76. self._stdio = stdio
  77. self._warningsModule = warningsModule
  78. self._temporaryObserver = LogPublisher(
  79. self._initialBuffer,
  80. FilteringLogObserver(
  81. FileLogObserver(
  82. errorStream,
  83. lambda event: eventAsText(
  84. event,
  85. includeTimestamp=False,
  86. includeSystem=False,
  87. ) + '\n'
  88. ),
  89. [LogLevelFilterPredicate(defaultLogLevel=LogLevel.critical)]
  90. )
  91. )
  92. publisher.addObserver(self._temporaryObserver)
  93. self._oldshowwarning = warningsModule.showwarning
  94. def beginLoggingTo(
  95. self, observers, discardBuffer=False, redirectStandardIO=True
  96. ):
  97. """
  98. Begin logging to the given set of observers. This will:
  99. 1. Add all the observers given in C{observers} to the
  100. L{LogPublisher} associated with this L{LogBeginner}.
  101. 2. Optionally re-direct standard output and standard error streams
  102. to the logging system.
  103. 3. Re-play any messages that were previously logged to that
  104. publisher to the new observers, if C{discardBuffer} is not set.
  105. 4. Stop logging critical errors from the L{LogPublisher} as strings
  106. to the C{errorStream} associated with this L{LogBeginner}, and
  107. allow them to be logged normally.
  108. 5. Re-direct warnings from the L{warnings} module associated with
  109. this L{LogBeginner} to log messages.
  110. @note: Since a L{LogBeginner} is designed to encapsulate the transition
  111. between process-startup and log-system-configuration, this method
  112. is intended to be invoked I{once}.
  113. @param observers: The observers to register.
  114. @type observers: iterable of L{ILogObserver}s
  115. @param discardBuffer: Whether to discard the buffer and not re-play it
  116. to the added observers. (This argument is provided mainly for
  117. compatibility with legacy concerns.)
  118. @type discardBuffer: L{bool}
  119. @param redirectStandardIO: If true, redirect standard output and
  120. standard error to the observers.
  121. @type redirectStandardIO: L{bool}
  122. """
  123. caller = currentframe(1)
  124. filename, lineno = caller.f_code.co_filename, caller.f_lineno
  125. for observer in observers:
  126. self._publisher.addObserver(observer)
  127. if self._temporaryObserver is not None:
  128. self._publisher.removeObserver(self._temporaryObserver)
  129. if not discardBuffer:
  130. self._initialBuffer.replayTo(self._publisher)
  131. self._temporaryObserver = None
  132. self._warningsModule.showwarning = self.showwarning
  133. else:
  134. previousFile, previousLine = self._previousBegin
  135. self._log.warn(
  136. MORE_THAN_ONCE_WARNING,
  137. fileNow=filename, lineNow=lineno,
  138. fileThen=previousFile, lineThen=previousLine,
  139. )
  140. self._previousBegin = filename, lineno
  141. if redirectStandardIO:
  142. streams = [("stdout", LogLevel.info), ("stderr", LogLevel.error)]
  143. else:
  144. streams = []
  145. for (stream, level) in streams:
  146. oldStream = getattr(self._stdio, stream)
  147. loggingFile = LoggingFile(
  148. logger=Logger(namespace=stream, observer=self._publisher),
  149. level=level,
  150. encoding=getattr(oldStream, "encoding", None),
  151. )
  152. setattr(self._stdio, stream, loggingFile)
  153. def showwarning(
  154. self, message, category, filename, lineno, file=None, line=None
  155. ):
  156. """
  157. Twisted-enabled wrapper around L{warnings.showwarning}.
  158. If C{file} is L{None}, the default behaviour is to emit the warning to
  159. the log system, otherwise the original L{warnings.showwarning} Python
  160. function is called.
  161. @param message: A warning message to emit.
  162. @type message: L{str}
  163. @param category: A warning category to associate with C{message}.
  164. @type category: L{warnings.Warning}
  165. @param filename: A file name for the source code file issuing the
  166. warning.
  167. @type warning: L{str}
  168. @param lineno: A line number in the source file where the warning was
  169. issued.
  170. @type lineno: L{int}
  171. @param file: A file to write the warning message to. If L{None},
  172. write to L{sys.stderr}.
  173. @type file: file-like object
  174. @param line: A line of source code to include with the warning message.
  175. If L{None}, attempt to read the line from C{filename} and
  176. C{lineno}.
  177. @type line: L{str}
  178. """
  179. if file is None:
  180. self._log.warn(
  181. "{filename}:{lineno}: {category}: {warning}",
  182. warning=message, category=qual(category),
  183. filename=filename, lineno=lineno,
  184. )
  185. else:
  186. self._oldshowwarning(
  187. message, category, filename, lineno, file, line
  188. )
  189. globalLogPublisher = LogPublisher()
  190. globalLogBeginner = LogBeginner(globalLogPublisher, sys.stderr, sys, warnings)