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.

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. # -*- test-case-name: twisted.test.test_log -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Logging and metrics infrastructure.
  6. """
  7. from __future__ import division, absolute_import
  8. import sys
  9. import time
  10. import warnings
  11. from datetime import datetime
  12. from zope.interface import Interface
  13. from twisted.python.compat import unicode, _PY3
  14. from twisted.python import context
  15. from twisted.python import reflect
  16. from twisted.python import util
  17. from twisted.python import failure
  18. from twisted.python._oldstyle import _oldStyle
  19. from twisted.python.threadable import synchronize
  20. from twisted.logger import (
  21. Logger as NewLogger, LogLevel as NewLogLevel,
  22. STDLibLogObserver as NewSTDLibLogObserver,
  23. LegacyLogObserverWrapper, LoggingFile, LogPublisher as NewPublisher,
  24. globalLogPublisher as newGlobalLogPublisher,
  25. globalLogBeginner as newGlobalLogBeginner,
  26. )
  27. from twisted.logger._global import LogBeginner
  28. from twisted.logger._legacy import publishToNewObserver as _publishNew
  29. @_oldStyle
  30. class ILogContext:
  31. """
  32. Actually, this interface is just a synonym for the dictionary interface,
  33. but it serves as a key for the default information in a log.
  34. I do not inherit from C{Interface} because the world is a cruel place.
  35. """
  36. class ILogObserver(Interface):
  37. """
  38. An observer which can do something with log events.
  39. Given that most log observers are actually bound methods, it's okay to not
  40. explicitly declare provision of this interface.
  41. """
  42. def __call__(eventDict):
  43. """
  44. Log an event.
  45. @type eventDict: C{dict} with C{str} keys.
  46. @param eventDict: A dictionary with arbitrary keys. However, these
  47. keys are often available:
  48. - C{message}: A C{tuple} of C{str} containing messages to be
  49. logged.
  50. - C{system}: A C{str} which indicates the "system" which is
  51. generating this event.
  52. - C{isError}: A C{bool} indicating whether this event represents
  53. an error.
  54. - C{failure}: A L{failure.Failure} instance
  55. - C{why}: Used as header of the traceback in case of errors.
  56. - C{format}: A string format used in place of C{message} to
  57. customize the event. The intent is for the observer to format
  58. a message by doing something like C{format % eventDict}.
  59. """
  60. context.setDefault(ILogContext,
  61. {"system": "-"})
  62. def callWithContext(ctx, func, *args, **kw):
  63. newCtx = context.get(ILogContext).copy()
  64. newCtx.update(ctx)
  65. return context.call({ILogContext: newCtx}, func, *args, **kw)
  66. def callWithLogger(logger, func, *args, **kw):
  67. """
  68. Utility method which wraps a function in a try:/except:, logs a failure if
  69. one occurs, and uses the system's logPrefix.
  70. """
  71. try:
  72. lp = logger.logPrefix()
  73. except KeyboardInterrupt:
  74. raise
  75. except:
  76. lp = '(buggy logPrefix method)'
  77. err(system=lp)
  78. try:
  79. return callWithContext({"system": lp}, func, *args, **kw)
  80. except KeyboardInterrupt:
  81. raise
  82. except:
  83. err(system=lp)
  84. def err(_stuff=None, _why=None, **kw):
  85. """
  86. Write a failure to the log.
  87. The C{_stuff} and C{_why} parameters use an underscore prefix to lessen
  88. the chance of colliding with a keyword argument the application wishes
  89. to pass. It is intended that they be supplied with arguments passed
  90. positionally, not by keyword.
  91. @param _stuff: The failure to log. If C{_stuff} is L{None} a new
  92. L{Failure} will be created from the current exception state. If
  93. C{_stuff} is an C{Exception} instance it will be wrapped in a
  94. L{Failure}.
  95. @type _stuff: L{None}, C{Exception}, or L{Failure}.
  96. @param _why: The source of this failure. This will be logged along with
  97. C{_stuff} and should describe the context in which the failure
  98. occurred.
  99. @type _why: C{str}
  100. """
  101. if _stuff is None:
  102. _stuff = failure.Failure()
  103. if isinstance(_stuff, failure.Failure):
  104. msg(failure=_stuff, why=_why, isError=1, **kw)
  105. elif isinstance(_stuff, Exception):
  106. msg(failure=failure.Failure(_stuff), why=_why, isError=1, **kw)
  107. else:
  108. msg(repr(_stuff), why=_why, isError=1, **kw)
  109. deferr = err
  110. @_oldStyle
  111. class Logger:
  112. """
  113. This represents a class which may 'own' a log. Used by subclassing.
  114. """
  115. def logPrefix(self):
  116. """
  117. Override this method to insert custom logging behavior. Its
  118. return value will be inserted in front of every line. It may
  119. be called more times than the number of output lines.
  120. """
  121. return '-'
  122. @_oldStyle
  123. class LogPublisher:
  124. """
  125. Class for singleton log message publishing.
  126. """
  127. synchronized = ['msg']
  128. def __init__(self, observerPublisher=None, publishPublisher=None,
  129. logBeginner=None, warningsModule=warnings):
  130. if publishPublisher is None:
  131. publishPublisher = NewPublisher()
  132. if observerPublisher is None:
  133. observerPublisher = publishPublisher
  134. if observerPublisher is None:
  135. observerPublisher = NewPublisher()
  136. self._observerPublisher = observerPublisher
  137. self._publishPublisher = publishPublisher
  138. self._legacyObservers = []
  139. if logBeginner is None:
  140. # This default behavior is really only used for testing.
  141. beginnerPublisher = NewPublisher()
  142. beginnerPublisher.addObserver(observerPublisher)
  143. logBeginner = LogBeginner(beginnerPublisher, NullFile(), sys,
  144. warnings)
  145. self._logBeginner = logBeginner
  146. self._warningsModule = warningsModule
  147. self._oldshowwarning = warningsModule.showwarning
  148. self.showwarning = self._logBeginner.showwarning
  149. @property
  150. def observers(self):
  151. """
  152. Property returning all observers registered on this L{LogPublisher}.
  153. @return: observers previously added with L{LogPublisher.addObserver}
  154. @rtype: L{list} of L{callable}
  155. """
  156. return [x.legacyObserver for x in self._legacyObservers]
  157. def _startLogging(self, other, setStdout):
  158. """
  159. Begin logging to the L{LogBeginner} associated with this
  160. L{LogPublisher}.
  161. @param other: the observer to log to.
  162. @type other: L{LogBeginner}
  163. @param setStdout: if true, send standard I/O to the observer as well.
  164. @type setStdout: L{bool}
  165. """
  166. wrapped = LegacyLogObserverWrapper(other)
  167. self._legacyObservers.append(wrapped)
  168. self._logBeginner.beginLoggingTo([wrapped], True, setStdout)
  169. def _stopLogging(self):
  170. """
  171. Clean-up hook for fixing potentially global state. Only for testing of
  172. this module itself. If you want less global state, use the new
  173. warnings system in L{twisted.logger}.
  174. """
  175. if self._warningsModule.showwarning == self.showwarning:
  176. self._warningsModule.showwarning = self._oldshowwarning
  177. def addObserver(self, other):
  178. """
  179. Add a new observer.
  180. @type other: Provider of L{ILogObserver}
  181. @param other: A callable object that will be called with each new log
  182. message (a dict).
  183. """
  184. wrapped = LegacyLogObserverWrapper(other)
  185. self._legacyObservers.append(wrapped)
  186. self._observerPublisher.addObserver(wrapped)
  187. def removeObserver(self, other):
  188. """
  189. Remove an observer.
  190. """
  191. for observer in self._legacyObservers:
  192. if observer.legacyObserver == other:
  193. self._legacyObservers.remove(observer)
  194. self._observerPublisher.removeObserver(observer)
  195. break
  196. def msg(self, *message, **kw):
  197. """
  198. Log a new message.
  199. The message should be a native string, i.e. bytes on Python 2 and
  200. Unicode on Python 3. For compatibility with both use the native string
  201. syntax, for example::
  202. >>> log.msg('Hello, world.')
  203. You MUST avoid passing in Unicode on Python 2, and the form::
  204. >>> log.msg('Hello ', 'world.')
  205. This form only works (sometimes) by accident.
  206. Keyword arguments will be converted into items in the event
  207. dict that is passed to L{ILogObserver} implementations.
  208. Each implementation, in turn, can define keys that are used
  209. by it specifically, in addition to common keys listed at
  210. L{ILogObserver.__call__}.
  211. For example, to set the C{system} parameter while logging
  212. a message::
  213. >>> log.msg('Started', system='Foo')
  214. """
  215. actualEventDict = (context.get(ILogContext) or {}).copy()
  216. actualEventDict.update(kw)
  217. actualEventDict['message'] = message
  218. actualEventDict['time'] = time.time()
  219. if "isError" not in actualEventDict:
  220. actualEventDict["isError"] = 0
  221. _publishNew(self._publishPublisher, actualEventDict, textFromEventDict)
  222. synchronize(LogPublisher)
  223. if 'theLogPublisher' not in globals():
  224. def _actually(something):
  225. """
  226. A decorator that returns its argument rather than the thing it is
  227. decorating.
  228. This allows the documentation generator to see an alias for a method or
  229. constant as an object with a docstring and thereby document it and
  230. allow references to it statically.
  231. @param something: An object to create an alias for.
  232. @type something: L{object}
  233. @return: a 1-argument callable that returns C{something}
  234. @rtype: L{object}
  235. """
  236. def decorate(thingWithADocstring):
  237. return something
  238. return decorate
  239. theLogPublisher = LogPublisher(
  240. observerPublisher=newGlobalLogPublisher,
  241. publishPublisher=newGlobalLogPublisher,
  242. logBeginner=newGlobalLogBeginner,
  243. )
  244. @_actually(theLogPublisher.addObserver)
  245. def addObserver(observer):
  246. """
  247. Add a log observer to the global publisher.
  248. @see: L{LogPublisher.addObserver}
  249. @param observer: a log observer
  250. @type observer: L{callable}
  251. """
  252. @_actually(theLogPublisher.removeObserver)
  253. def removeObserver(observer):
  254. """
  255. Remove a log observer from the global publisher.
  256. @see: L{LogPublisher.removeObserver}
  257. @param observer: a log observer previously added with L{addObserver}
  258. @type observer: L{callable}
  259. """
  260. @_actually(theLogPublisher.msg)
  261. def msg(*message, **event):
  262. """
  263. Publish a message to the global log publisher.
  264. @see: L{LogPublisher.msg}
  265. @param message: the log message
  266. @type message: C{tuple} of L{str} (native string)
  267. @param event: fields for the log event
  268. @type event: L{dict} mapping L{str} (native string) to L{object}
  269. """
  270. @_actually(theLogPublisher.showwarning)
  271. def showwarning():
  272. """
  273. Publish a Python warning through the global log publisher.
  274. @see: L{LogPublisher.showwarning}
  275. """
  276. def _safeFormat(fmtString, fmtDict):
  277. """
  278. Try to format a string, swallowing all errors to always return a string.
  279. @note: For backward-compatibility reasons, this function ensures that it
  280. returns a native string, meaning C{bytes} in Python 2 and C{unicode} in
  281. Python 3.
  282. @param fmtString: a C{%}-format string
  283. @param fmtDict: string formatting arguments for C{fmtString}
  284. @return: A native string, formatted from C{fmtString} and C{fmtDict}.
  285. @rtype: L{str}
  286. """
  287. # There's a way we could make this if not safer at least more
  288. # informative: perhaps some sort of str/repr wrapper objects
  289. # could be wrapped around the things inside of C{fmtDict}. That way
  290. # if the event dict contains an object with a bad __repr__, we
  291. # can only cry about that individual object instead of the
  292. # entire event dict.
  293. try:
  294. text = fmtString % fmtDict
  295. except KeyboardInterrupt:
  296. raise
  297. except:
  298. try:
  299. text = ('Invalid format string or unformattable object in '
  300. 'log message: %r, %s' % (fmtString, fmtDict))
  301. except:
  302. try:
  303. text = ('UNFORMATTABLE OBJECT WRITTEN TO LOG with fmt %r, '
  304. 'MESSAGE LOST' % (fmtString,))
  305. except:
  306. text = ('PATHOLOGICAL ERROR IN BOTH FORMAT STRING AND '
  307. 'MESSAGE DETAILS, MESSAGE LOST')
  308. # Return a native string
  309. if _PY3:
  310. if isinstance(text, bytes):
  311. text = text.decode("utf-8")
  312. else:
  313. if isinstance(text, unicode):
  314. text = text.encode("utf-8")
  315. return text
  316. def textFromEventDict(eventDict):
  317. """
  318. Extract text from an event dict passed to a log observer. If it cannot
  319. handle the dict, it returns None.
  320. The possible keys of eventDict are:
  321. - C{message}: by default, it holds the final text. It's required, but can
  322. be empty if either C{isError} or C{format} is provided (the first
  323. having the priority).
  324. - C{isError}: boolean indicating the nature of the event.
  325. - C{failure}: L{failure.Failure} instance, required if the event is an
  326. error.
  327. - C{why}: if defined, used as header of the traceback in case of errors.
  328. - C{format}: string format used in place of C{message} to customize
  329. the event. It uses all keys present in C{eventDict} to format
  330. the text.
  331. Other keys will be used when applying the C{format}, or ignored.
  332. """
  333. edm = eventDict['message']
  334. if not edm:
  335. if eventDict['isError'] and 'failure' in eventDict:
  336. why = eventDict.get('why')
  337. if why:
  338. why = reflect.safe_str(why)
  339. else:
  340. why = 'Unhandled Error'
  341. try:
  342. traceback = eventDict['failure'].getTraceback()
  343. except Exception as e:
  344. traceback = '(unable to obtain traceback): ' + str(e)
  345. text = (why + '\n' + traceback)
  346. elif 'format' in eventDict:
  347. text = _safeFormat(eventDict['format'], eventDict)
  348. else:
  349. # We don't know how to log this
  350. return None
  351. else:
  352. text = ' '.join(map(reflect.safe_str, edm))
  353. return text
  354. @_oldStyle
  355. class _GlobalStartStopMixIn:
  356. """
  357. Mix-in for global log observers that can start and stop.
  358. """
  359. def start(self):
  360. """
  361. Start observing log events.
  362. """
  363. addObserver(self.emit)
  364. def stop(self):
  365. """
  366. Stop observing log events.
  367. """
  368. removeObserver(self.emit)
  369. class FileLogObserver(_GlobalStartStopMixIn):
  370. """
  371. Log observer that writes to a file-like object.
  372. @type timeFormat: C{str} or L{None}
  373. @ivar timeFormat: If not L{None}, the format string passed to strftime().
  374. """
  375. timeFormat = None
  376. def __init__(self, f):
  377. # Compatibility
  378. self.write = f.write
  379. self.flush = f.flush
  380. def getTimezoneOffset(self, when):
  381. """
  382. Return the current local timezone offset from UTC.
  383. @type when: C{int}
  384. @param when: POSIX (ie, UTC) timestamp for which to find the offset.
  385. @rtype: C{int}
  386. @return: The number of seconds offset from UTC. West is positive,
  387. east is negative.
  388. """
  389. offset = datetime.utcfromtimestamp(when) - datetime.fromtimestamp(when)
  390. return offset.days * (60 * 60 * 24) + offset.seconds
  391. def formatTime(self, when):
  392. """
  393. Format the given UTC value as a string representing that time in the
  394. local timezone.
  395. By default it's formatted as an ISO8601-like string (ISO8601 date and
  396. ISO8601 time separated by a space). It can be customized using the
  397. C{timeFormat} attribute, which will be used as input for the underlying
  398. L{datetime.datetime.strftime} call.
  399. @type when: C{int}
  400. @param when: POSIX (ie, UTC) timestamp for which to find the offset.
  401. @rtype: C{str}
  402. """
  403. if self.timeFormat is not None:
  404. return datetime.fromtimestamp(when).strftime(self.timeFormat)
  405. tzOffset = -self.getTimezoneOffset(when)
  406. when = datetime.utcfromtimestamp(when + tzOffset)
  407. tzHour = abs(int(tzOffset / 60 / 60))
  408. tzMin = abs(int(tzOffset / 60 % 60))
  409. if tzOffset < 0:
  410. tzSign = '-'
  411. else:
  412. tzSign = '+'
  413. return '%d-%02d-%02d %02d:%02d:%02d%s%02d%02d' % (
  414. when.year, when.month, when.day,
  415. when.hour, when.minute, when.second,
  416. tzSign, tzHour, tzMin)
  417. def emit(self, eventDict):
  418. """
  419. Format the given log event as text and write it to the output file.
  420. @param eventDict: a log event
  421. @type eventDict: L{dict} mapping L{str} (native string) to L{object}
  422. """
  423. text = textFromEventDict(eventDict)
  424. if text is None:
  425. return
  426. timeStr = self.formatTime(eventDict["time"])
  427. fmtDict = {
  428. "system": eventDict["system"],
  429. "text": text.replace("\n", "\n\t")
  430. }
  431. msgStr = _safeFormat("[%(system)s] %(text)s\n", fmtDict)
  432. util.untilConcludes(self.write, timeStr + " " + msgStr)
  433. util.untilConcludes(self.flush) # Hoorj!
  434. class PythonLoggingObserver(_GlobalStartStopMixIn, object):
  435. """
  436. Output twisted messages to Python standard library L{logging} module.
  437. WARNING: specific logging configurations (example: network) can lead to
  438. a blocking system. Nothing is done here to prevent that, so be sure to not
  439. use this: code within Twisted, such as twisted.web, assumes that logging
  440. does not block.
  441. """
  442. def __init__(self, loggerName="twisted"):
  443. """
  444. @param loggerName: identifier used for getting logger.
  445. @type loggerName: C{str}
  446. """
  447. self._newObserver = NewSTDLibLogObserver(loggerName)
  448. def emit(self, eventDict):
  449. """
  450. Receive a twisted log entry, format it and bridge it to python.
  451. By default the logging level used is info; log.err produces error
  452. level, and you can customize the level by using the C{logLevel} key::
  453. >>> log.msg('debugging', logLevel=logging.DEBUG)
  454. """
  455. if 'log_format' in eventDict:
  456. _publishNew(self._newObserver, eventDict, textFromEventDict)
  457. @_oldStyle
  458. class StdioOnnaStick:
  459. """
  460. Class that pretends to be stdout/err, and turns writes into log messages.
  461. @ivar isError: boolean indicating whether this is stderr, in which cases
  462. log messages will be logged as errors.
  463. @ivar encoding: unicode encoding used to encode any unicode strings
  464. written to this object.
  465. """
  466. closed = 0
  467. softspace = 0
  468. mode = 'wb'
  469. name = '<stdio (log)>'
  470. def __init__(self, isError=0, encoding=None):
  471. self.isError = isError
  472. if encoding is None:
  473. encoding = sys.getdefaultencoding()
  474. self.encoding = encoding
  475. self.buf = ''
  476. def close(self):
  477. pass
  478. def fileno(self):
  479. return -1
  480. def flush(self):
  481. pass
  482. def read(self):
  483. raise IOError("can't read from the log!")
  484. readline = read
  485. readlines = read
  486. seek = read
  487. tell = read
  488. def write(self, data):
  489. if not _PY3 and isinstance(data, unicode):
  490. data = data.encode(self.encoding)
  491. d = (self.buf + data).split('\n')
  492. self.buf = d[-1]
  493. messages = d[0:-1]
  494. for message in messages:
  495. msg(message, printed=1, isError=self.isError)
  496. def writelines(self, lines):
  497. for line in lines:
  498. if not _PY3 and isinstance(line, unicode):
  499. line = line.encode(self.encoding)
  500. msg(line, printed=1, isError=self.isError)
  501. def startLogging(file, *a, **kw):
  502. """
  503. Initialize logging to a specified file.
  504. @return: A L{FileLogObserver} if a new observer is added, None otherwise.
  505. """
  506. if isinstance(file, LoggingFile):
  507. return
  508. flo = FileLogObserver(file)
  509. startLoggingWithObserver(flo.emit, *a, **kw)
  510. return flo
  511. def startLoggingWithObserver(observer, setStdout=1):
  512. """
  513. Initialize logging to a specified observer. If setStdout is true
  514. (defaults to yes), also redirect sys.stdout and sys.stderr
  515. to the specified file.
  516. """
  517. theLogPublisher._startLogging(observer, setStdout)
  518. msg("Log opened.")
  519. @_oldStyle
  520. class NullFile:
  521. """
  522. A file-like object that discards everything.
  523. """
  524. softspace = 0
  525. def read(self):
  526. """
  527. Do nothing.
  528. """
  529. def write(self, bytes):
  530. """
  531. Do nothing.
  532. @param bytes: data
  533. @type bytes: L{bytes}
  534. """
  535. def flush(self):
  536. """
  537. Do nothing.
  538. """
  539. def close(self):
  540. """
  541. Do nothing.
  542. """
  543. def discardLogs():
  544. """
  545. Discard messages logged via the global C{logfile} object.
  546. """
  547. global logfile
  548. logfile = NullFile()
  549. # Prevent logfile from being erased on reload. This only works in cpython.
  550. if 'logfile' not in globals():
  551. logfile = LoggingFile(logger=NewLogger(),
  552. level=NewLogLevel.info,
  553. encoding=getattr(sys.stdout, "encoding", None))
  554. logerr = LoggingFile(logger=NewLogger(),
  555. level=NewLogLevel.error,
  556. encoding=getattr(sys.stderr, "encoding", None))
  557. class DefaultObserver(_GlobalStartStopMixIn):
  558. """
  559. Default observer.
  560. Will ignore all non-error messages and send error messages to sys.stderr.
  561. Will be removed when startLogging() is called for the first time.
  562. """
  563. stderr = sys.stderr
  564. def emit(self, eventDict):
  565. """
  566. Emit an event dict.
  567. @param eventDict: an event dict
  568. @type eventDict: dict
  569. """
  570. if eventDict["isError"]:
  571. text = textFromEventDict(eventDict)
  572. self.stderr.write(text)
  573. self.stderr.flush()
  574. if 'defaultObserver' not in globals():
  575. defaultObserver = DefaultObserver()