_util.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- test-case-name: twisted.logger.test.test_util -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Logging utilities.
  6. """
  7. from typing import List
  8. from ._interfaces import LogTrace
  9. from ._logger import Logger
  10. def formatTrace(trace: LogTrace) -> str:
  11. """
  12. Format a trace (that is, the contents of the C{log_trace} key of a log
  13. event) as a visual indication of the message's propagation through various
  14. observers.
  15. @param trace: the contents of the C{log_trace} key from an event.
  16. @return: A multi-line string with indentation and arrows indicating the
  17. flow of the message through various observers.
  18. """
  19. def formatWithName(obj: object) -> str:
  20. if hasattr(obj, "name"):
  21. return f"{obj} ({obj.name})"
  22. else:
  23. return f"{obj}"
  24. result = []
  25. lineage: List[Logger] = []
  26. for parent, child in trace:
  27. if not lineage or lineage[-1] is not parent:
  28. if parent in lineage:
  29. while lineage[-1] is not parent:
  30. lineage.pop()
  31. else:
  32. if not lineage:
  33. result.append(f"{formatWithName(parent)}\n")
  34. lineage.append(parent)
  35. result.append(" " * len(lineage))
  36. result.append(f"-> {formatWithName(child)}\n")
  37. return "".join(result)