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

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

2 import logging

3 from contextvars import ContextVar

4 from typing import Any, MutableMapping, Optional, Tuple

5

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

7

8

9 class IndentedLoggerAdapter(logging.LoggerAdapter):

10 """

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

12

13 Parameters:

14 logger: The logger to adapt.

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

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

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

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

19 """

20

21 def __init__(

22 self,

23 logger: logging.Logger,

24 extra: Optional[dict] = None,

25 depth: int = 2,

26 indent_char: str = " ",

27 reset: bool = False,

28 ):

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

30 self._depth = depth

31 self._indent_char = indent_char

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

33 self.reset()

34

35 @property

36 def current_indent(self) -> int:

37 """

38 The current indent level.

39 """

40 return CURRENT_INDENT.get()

41

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

43 """

44 Increase the indent level by `amount`.

45 """

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

47

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

49 """

50 Decrease the indent level by `amount`.

51 """

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

53

54 def reset(self) -> None:

55 """

56 Reset the indent level to zero.

57 """

58 CURRENT_INDENT.set(0)

59

60 @property

61 def indent_str(self) -> str:

62 """

63 The indent string.

64 """

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

66

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

68 """

69 Process the message and add the indent.

70

71 Args:

72 msg: The logging message.

73 kwargs: Keyword arguments passed to the logger.

74

75 Returns:

76 A tuple containing the message and keyword arguments.

77 """

78 msg = self.indent_str + msg

79

80 return msg, kwargs