|
1 | 1 | __author__ = "desultory" |
2 | | -__version__ = "2.0.0" |
3 | | - |
| 2 | +__version__ = "3.0.0" |
4 | 3 |
|
5 | 4 | from logging import Formatter |
6 | 5 |
|
| 6 | +from zenlib.util import colorize |
7 | 7 |
|
8 | | -class ColorLognameFormatter(Formatter): |
9 | | - """ |
10 | | - ColorLognameFormatter Class |
11 | | - Add the handler to the stdout handler using: |
12 | | - stdout_handler = logging.StreamHandler() |
13 | | - stdout_handler.setFormatter(ColorLognameFormatter()) |
14 | | - """ |
15 | | - |
16 | | - # Define the color codes |
17 | | - _reset_str = '\x1b[0m' |
18 | | - _grey_str = '\x1b[37m' |
19 | | - _blue_str = '\x1b[34m' |
20 | | - _yllw_str = '\x1b[33m' |
21 | | - _sred_str = '\x1b[31m' |
22 | | - _bred_str = '\x1b[31;1m' |
23 | | - _magenta_str = '\x1b[35m' |
24 | | - # Format into a dict |
25 | | - _color_levelname = {'DEBUG': _grey_str, |
26 | | - 'INFO': _blue_str, |
27 | | - 'WARNING': _yllw_str, |
28 | | - 'ERROR': _sred_str, |
29 | | - 'CRITICAL': _bred_str} |
30 | 8 |
|
31 | | - def __init__(self, fmt='%(levelname)s | %(message)s', *args, **kwargs): |
| 9 | +class ColorLognameFormatter(Formatter): |
| 10 | + """A logging formatter which colors the levelname of the log message. |
| 11 | + Uses the zenlib.util.colorize function to color the levelname. |
| 12 | + Normal levelnames are padded to the length of the longest levelname.""" |
| 13 | + |
| 14 | + level_colors = { |
| 15 | + "DEBUG": {"color": "white"}, |
| 16 | + "INFO": {"color": "blue"}, |
| 17 | + "WARNING": {"color": "yellow"}, |
| 18 | + "ERROR": {"color": "red", "bold": True}, |
| 19 | + "CRITICAL": {"color": "red", "bold": True, "bright": True}, |
| 20 | + } |
| 21 | + |
| 22 | + def __init__(self, fmt="%(levelname)s | %(message)s", *args, **kwargs): |
32 | 23 | super().__init__(fmt, *args, **kwargs) |
33 | | - self._level_str_len = max([len(name) for name in self._color_levelname]) |
34 | | - |
35 | | - def color_levelname(self, levelname): |
36 | | - """ Adds color to a levelname string """ |
37 | | - color = self._color_levelname.get(levelname, self._magenta_str) |
38 | | - return f"{color}{levelname}{self._reset_str}".ljust(self._level_str_len + len(color) + len(self._reset_str), ' ') |
| 24 | + self.level_str_width = max(len(name) for name in self.level_colors) - 1 |
39 | 25 |
|
40 | 26 | def format(self, record): |
41 | 27 | # When calling format, replace the levelname with a colored version |
42 | 28 | # Note: the string size is greatly increased because of the color codes |
43 | 29 | old_levelname = record.levelname |
44 | | - record.levelname = self.color_levelname(record.levelname) |
| 30 | + color_info = self.level_colors.get(record.levelname, {"color": "white"}) |
| 31 | + record.levelname = colorize(record.levelname.ljust(self.level_str_width), **color_info) |
45 | 32 | format_str = super().format(record) |
46 | 33 | record.levelname = old_levelname |
47 | 34 | return format_str |
0 commit comments