Coverage for gsb/logging.py: 100%

13 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-08 20:16 +0000

1"""Common logging utilities""" 

2 

3import logging 

4 

5IMPORTANT = 25 # INFO logs that should be displayed even without "-v" 

6logging.addLevelName(IMPORTANT, "INFO") 

7 

8 

9class CLIFormatter(logging.Formatter): 

10 """Colorful formatter for the CLI 

11 

12 h/t https://stackoverflow.com/a/56944256 

13 """ 

14 

15 grey = "\x1b[2;20m" 

16 yellow = "\x1b[33;20m" 

17 bold_red = "\x1b[31;1m" 

18 reset = "\x1b[0m" 

19 

20 FORMATS = { 

21 logging.DEBUG: grey + "%(message)s" + reset, 

22 logging.INFO: "%(message)s", 

23 IMPORTANT: "%(message)s", 

24 logging.WARNING: yellow + "%(message)s" + reset, 

25 logging.ERROR: bold_red + "%(message)s" + reset, 

26 logging.CRITICAL: bold_red + "%(message)s" + reset, 

27 } 

28 

29 def format(self, record: logging.LogRecord) -> str: 

30 return logging.Formatter(self.FORMATS.get(record.levelno)).format(record) 

31 

32 

33def verbosity_to_log_level(verbosity: int) -> int: 

34 """Convert a verbosity level (number of `-v`s minus number of `-q`s) to 

35 a logging level 

36 

37 Parameters 

38 ---------- 

39 verbosity: int 

40 A verbosity level usually specified by the number of `-v` flags a user 

41 provides minus the number of `-q` flags. As a baseline, a verbosity of 

42 0 will set the level to handle all messages above (excluding) the 

43 INFO level. 

44 

45 Returns 

46 ------- 

47 int 

48 The corresponding log level that should be set 

49 

50 Notes 

51 ----- 

52 Technically the default logging level is set just high enough to exclude 

53 DEBUG by default. This allows us to capture intermediate log levels (read: 

54 `IMPORTANT`) at the `verbosity = -1` (`-q`) level. 

55 """ 

56 return logging.INFO + 1 - 10 * verbosity