_legacy.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # -*- test-case-name: twisted.logger.test.test_legacy -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Integration with L{twisted.python.log}.
  6. """
  7. from typing import TYPE_CHECKING, Any, Callable, Dict, Optional
  8. from zope.interface import implementer
  9. from ._format import formatEvent
  10. from ._interfaces import ILogObserver, LogEvent
  11. from ._levels import LogLevel
  12. from ._stdlib import StringifiableFromEvent, fromStdlibLogLevelMapping
  13. if TYPE_CHECKING:
  14. from twisted.python.log import ILogObserver as ILegacyLogObserver
  15. @implementer(ILogObserver)
  16. class LegacyLogObserverWrapper:
  17. """
  18. L{ILogObserver} that wraps a L{twisted.python.log.ILogObserver}.
  19. Received (new-style) events are modified prior to forwarding to
  20. the legacy observer to ensure compatibility with observers that
  21. expect legacy events.
  22. """
  23. def __init__(self, legacyObserver: "ILegacyLogObserver") -> None:
  24. """
  25. @param legacyObserver: a legacy observer to which this observer will
  26. forward events.
  27. """
  28. self.legacyObserver = legacyObserver
  29. def __repr__(self) -> str:
  30. return "{self.__class__.__name__}({self.legacyObserver})".format(self=self)
  31. def __call__(self, event: LogEvent) -> None:
  32. """
  33. Forward events to the legacy observer after editing them to
  34. ensure compatibility.
  35. @param event: an event
  36. """
  37. # The "message" key is required by textFromEventDict()
  38. if "message" not in event:
  39. event["message"] = ()
  40. if "time" not in event:
  41. event["time"] = event["log_time"]
  42. if "system" not in event:
  43. event["system"] = event.get("log_system", "-")
  44. # Format new style -> old style
  45. if "format" not in event and event.get("log_format", None) is not None:
  46. # Create an object that implements __str__() in order to defer the
  47. # work of formatting until it's needed by a legacy log observer.
  48. event["format"] = "%(log_legacy)s"
  49. event["log_legacy"] = StringifiableFromEvent(event.copy())
  50. # In the old-style system, the 'message' key always holds a tuple
  51. # of messages. If we find the 'message' key here to not be a
  52. # tuple, it has been passed as new-style parameter. We drop it
  53. # here because we render it using the old-style 'format' key,
  54. # which otherwise doesn't get precedence, and the original event
  55. # has been copied above.
  56. if not isinstance(event["message"], tuple):
  57. event["message"] = ()
  58. # From log.failure() -> isError blah blah
  59. if "log_failure" in event:
  60. if "failure" not in event:
  61. event["failure"] = event["log_failure"]
  62. if "isError" not in event:
  63. event["isError"] = 1
  64. if "why" not in event:
  65. event["why"] = formatEvent(event)
  66. elif "isError" not in event:
  67. if event["log_level"] in (LogLevel.error, LogLevel.critical):
  68. event["isError"] = 1
  69. else:
  70. event["isError"] = 0
  71. self.legacyObserver(event)
  72. def publishToNewObserver(
  73. observer: ILogObserver,
  74. eventDict: Dict[str, Any],
  75. textFromEventDict: Callable[[Dict[str, Any]], Optional[str]],
  76. ) -> None:
  77. """
  78. Publish an old-style (L{twisted.python.log}) event to a new-style
  79. (L{twisted.logger}) observer.
  80. @note: It's possible that a new-style event was sent to a
  81. L{LegacyLogObserverWrapper}, and may now be getting sent back to a
  82. new-style observer. In this case, it's already a new-style event,
  83. adapted to also look like an old-style event, and we don't need to
  84. tweak it again to be a new-style event, hence this checks for
  85. already-defined new-style keys.
  86. @param observer: A new-style observer to handle this event.
  87. @param eventDict: An L{old-style <twisted.python.log>}, log event.
  88. @param textFromEventDict: callable that can format an old-style event as a
  89. string. Passed here rather than imported to avoid circular dependency.
  90. """
  91. if "log_time" not in eventDict:
  92. eventDict["log_time"] = eventDict["time"]
  93. if "log_format" not in eventDict:
  94. text = textFromEventDict(eventDict)
  95. if text is not None:
  96. eventDict["log_text"] = text
  97. eventDict["log_format"] = "{log_text}"
  98. if "log_level" not in eventDict:
  99. if "logLevel" in eventDict:
  100. try:
  101. level = fromStdlibLogLevelMapping[eventDict["logLevel"]]
  102. except KeyError:
  103. level = None
  104. elif "isError" in eventDict:
  105. if eventDict["isError"]:
  106. level = LogLevel.critical
  107. else:
  108. level = LogLevel.info
  109. else:
  110. level = LogLevel.info
  111. if level is not None:
  112. eventDict["log_level"] = level
  113. if "log_namespace" not in eventDict:
  114. eventDict["log_namespace"] = "log_legacy"
  115. if "log_system" not in eventDict and "system" in eventDict:
  116. eventDict["log_system"] = eventDict["system"]
  117. observer(eventDict)