Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

log.py 22KB

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