koder aka kdanilov | 962ee5f | 2016-12-19 02:40:08 +0200 | [diff] [blame] | 1 | import yaml |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 2 | import logging |
koder aka kdanilov | 962ee5f | 2016-12-19 02:40:08 +0200 | [diff] [blame] | 3 | import logging.config |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 4 | from typing import Callable, IO, Optional |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 5 | |
| 6 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 7 | def color_me(color: int) -> Callable[[str], str]: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 8 | RESET_SEQ = "\033[0m" |
| 9 | COLOR_SEQ = "\033[1;%dm" |
| 10 | |
| 11 | color_seq = COLOR_SEQ % (30 + color) |
| 12 | |
| 13 | def closure(msg): |
| 14 | return color_seq + msg + RESET_SEQ |
| 15 | return closure |
| 16 | |
| 17 | |
| 18 | class ColoredFormatter(logging.Formatter): |
| 19 | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) |
| 20 | |
| 21 | colors = { |
| 22 | 'WARNING': color_me(YELLOW), |
| 23 | 'DEBUG': color_me(BLUE), |
| 24 | 'CRITICAL': color_me(YELLOW), |
| 25 | 'ERROR': color_me(RED) |
| 26 | } |
| 27 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 28 | def __init__(self, msg: str, use_color: bool=True, datefmt: str=None) -> None: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 29 | logging.Formatter.__init__(self, msg, datefmt=datefmt) |
| 30 | self.use_color = use_color |
| 31 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 32 | def format(self, record: logging.LogRecord) -> str: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 33 | orig = record.__dict__ |
| 34 | record.__dict__ = record.__dict__.copy() |
| 35 | levelname = record.levelname |
| 36 | |
| 37 | prn_name = levelname + ' ' * (8 - len(levelname)) |
| 38 | if levelname in self.colors: |
| 39 | record.levelname = self.colors[levelname](prn_name) |
| 40 | else: |
| 41 | record.levelname = prn_name |
| 42 | |
| 43 | # super doesn't work here in 2.6 O_o |
| 44 | res = logging.Formatter.format(self, record) |
| 45 | |
| 46 | # res = super(ColoredFormatter, self).format(record) |
| 47 | |
| 48 | # restore record, as it will be used by other formatters |
| 49 | record.__dict__ = orig |
| 50 | return res |