Coverage for /Users/OORDCOR/Documents/code/bump-my-version/bumpversion/indented_logger.py: 88%

1"""A logger adapter that adds an indent to the beginning of each message."""

2

3 import logging

4 from contextvars import ContextVar

5 from typing import Any, MutableMapping, Optional, Tuple

6

7 CURRENT_INDENT = ContextVar("current_indent", default=0)

8

9

10 class IndentedLoggerAdapter(logging.LoggerAdapter):

11 """

12 Logger adapter that adds an indent to the beginning of each message.

13

14 Parameters:

15 logger: The logger to adapt.

16 extra: Extra values to add to the logging context.

17 depth: The number of `indent_char` to generate for each indent level.

18 indent_char: The character or string to use for indenting.

19 reset: `True` if the indent level should be reset to zero.

20 """

21

22 def __init__(

23 self,

24 logger: logging.Logger,

25 extra: Optional[dict] = None,

26 depth: int = 2,

27 indent_char: str = " ",

28 reset: bool = False,

29 ):

30 super().__init__(logger, extra or {})

31 self._depth = depth

32 self._indent_char = indent_char

33 if reset: 33 ↛ 34line 33 didn't jump to line 34, because the condition on line 33 was never true

34 self.reset()

35

36 @property

37 def current_indent(self) -> int:

38 """

39 The current indent level.

40 """

41 return CURRENT_INDENT.get()

42

43 def indent(self, amount: int = 1) -> None:

44 """

45 Increase the indent level by `amount`.

46 """

47 CURRENT_INDENT.set(CURRENT_INDENT.get() + amount)

48

49 def dedent(self, amount: int = 1) -> None:

50 """

51 Decrease the indent level by `amount`.

52 """

53 CURRENT_INDENT.set(max(0, CURRENT_INDENT.get() - amount))

54

55 def reset(self) -> None:

56 """

57 Reset the indent level to zero.

58 """

59 CURRENT_INDENT.set(0)

60

61 @property

62 def indent_str(self) -> str:

63 """

64 The indent string.

65 """

66 return (self._indent_char * self._depth) * CURRENT_INDENT.get()

67

68 def process(self, msg: str, kwargs: Optional[MutableMapping[str, Any]]) -> Tuple[str, MutableMapping[str, Any]]:

69 """

70 Process the message and add the indent.

71

72 Args:

73 msg: The logging message.

74 kwargs: Keyword arguments passed to the logger.

75

76 Returns:

77 A tuple containing the message and keyword arguments.

78 """

79 msg = self.indent_str + msg

80

81 return msg, kwargs