aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/Twisted/py3/twisted/logger/_util.py
blob: e8f02ddd225bc2e9f23403fb70bd1a6f6bde68e3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# -*- test-case-name: twisted.logger.test.test_util -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Logging utilities.
"""

from typing import List

from ._interfaces import LogTrace
from ._logger import Logger


def formatTrace(trace: LogTrace) -> str:
    """
    Format a trace (that is, the contents of the C{log_trace} key of a log
    event) as a visual indication of the message's propagation through various
    observers.

    @param trace: the contents of the C{log_trace} key from an event.

    @return: A multi-line string with indentation and arrows indicating the
        flow of the message through various observers.
    """

    def formatWithName(obj: object) -> str:
        if hasattr(obj, "name"):
            return f"{obj} ({obj.name})"
        else:
            return f"{obj}"

    result = []
    lineage: List[Logger] = []

    for parent, child in trace:
        if not lineage or lineage[-1] is not parent:
            if parent in lineage:
                while lineage[-1] is not parent:
                    lineage.pop()

            else:
                if not lineage:
                    result.append(f"{formatWithName(parent)}\n")

                lineage.append(parent)

        result.append("  " * len(lineage))
        result.append(f"-> {formatWithName(child)}\n")

    return "".join(result)