Coverage for gsb/logging.py: 100%

13 statements  

« prev     ^ index     » next       coverage.py v7.2.6, created at 2024-09-08 16:23 -0400

1"""Common logging utilities""" 

2import logging 

3 

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

5logging.addLevelName(IMPORTANT, "INFO") 

6 

7 

8class CLIFormatter(logging.Formatter): 

9 """Colorful formatter for the CLI 

10 

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

12 """ 

13 

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

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

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

17 reset = "\x1b[0m" 

18 

19 FORMATS = { 

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

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

22 IMPORTANT: "%(message)s", 

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

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

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

26 } 

27 

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

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

30 

31 

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

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

34 a logging level 

35 

36 Parameters 

37 ---------- 

38 verbosity: int 

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

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

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

42 INFO level. 

43 

44 Returns 

45 ------- 

46 int 

47 The corresponding log level that should be set 

48 

49 Notes 

50 ----- 

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

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

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

54 """ 

55 return logging.INFO + 1 - 10 * verbosity