blob: 78f5ab3255033962838bde9102d18bdae4c2cd45 [file] [log] [blame]
savex4448e132018-04-25 15:51:14 +02001import logging
2
3
4def color_me(color):
5 RESET_SEQ = "\033[0m"
6 COLOR_SEQ = "\033[1;%dm"
7
8 color_seq = COLOR_SEQ % (30 + color)
9
10 def closure(msg):
11 return color_seq + msg + RESET_SEQ
12 return closure
13
14
15class ColoredFormatter(logging.Formatter):
16 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
17
18 colors = {
19 'INFO': color_me(WHITE),
20 'WARNING': color_me(YELLOW),
21 'DEBUG': color_me(BLUE),
22 'CRITICAL': color_me(YELLOW),
23 'ERROR': color_me(RED)
24 }
25
26 def __init__(self, msg, use_color=True, datefmt=None):
27 logging.Formatter.__init__(self, msg, datefmt=datefmt)
28 self.use_color = use_color
29
30 def format(self, record):
31 orig = record.__dict__
32 record.__dict__ = record.__dict__.copy()
33 levelname = record.levelname
34
35 prn_name = levelname + ' ' * (8 - len(levelname))
36 if levelname in self.colors:
37 record.levelname = self.colors[levelname](prn_name)
38 else:
39 record.levelname = prn_name
40
41 # super doesn't work here in 2.6 O_o
42 res = logging.Formatter.format(self, record)
43
44 # res = super(ColoredFormatter, self).format(record)
45
46 # restore record, as it will be used by other formatters
47 record.__dict__ = orig
48 return res
49
50
51def setup_loggers(name, def_level=logging.DEBUG, log_fname=None):
52
53 # Stream Handler
54 sh = logging.StreamHandler()
55 sh.setLevel(def_level)
56 log_format = '%(message)s'
57 colored_formatter = ColoredFormatter(log_format, datefmt="%H:%M:%S")
58 sh.setFormatter(colored_formatter)
59
60 # File handler
61 if log_fname is not None:
62 fh = logging.FileHandler(log_fname)
63 log_format = '%(asctime)s - %(levelname)8s - %(name)-15s - %(message)s'
64 formatter = logging.Formatter(log_format, datefmt="%H:%M:%S")
65 fh.setFormatter(formatter)
66 fh.setLevel(logging.DEBUG)
67 else:
68 fh = None
69
70 logger = logging.getLogger(name)
71 logger.setLevel(logging.DEBUG)
72 if len(logger.handlers) == 0:
73 logger.addHandler(fh)
74
75 logger_cli = logging.getLogger(name + ".cli")
76 logger_cli.setLevel(logging.DEBUG)
77 if len(logger_cli.handlers) == 0:
78 logger_cli.addHandler(sh)
79
80 return logger, logger_cli