blob: 43eff6b43642941ea338bc19ce147ab721ca08a7 [file] [log] [blame]
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +03001import 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 'WARNING': color_me(YELLOW),
20 'DEBUG': color_me(BLUE),
21 'CRITICAL': color_me(YELLOW),
22 'ERROR': color_me(RED)
23 }
24
25 def __init__(self, msg, use_color=True, datefmt=None):
26 logging.Formatter.__init__(self, msg, datefmt=datefmt)
27 self.use_color = use_color
28
29 def format(self, record):
30 orig = record.__dict__
31 record.__dict__ = record.__dict__.copy()
32 levelname = record.levelname
33
34 prn_name = levelname + ' ' * (8 - len(levelname))
35 if levelname in self.colors:
36 record.levelname = self.colors[levelname](prn_name)
37 else:
38 record.levelname = prn_name
39
40 # super doesn't work here in 2.6 O_o
41 res = logging.Formatter.format(self, record)
42
43 # res = super(ColoredFormatter, self).format(record)
44
45 # restore record, as it will be used by other formatters
46 record.__dict__ = orig
47 return res
48
49
50def setup_loggers(def_level=logging.DEBUG, log_fname=None):
51 logger = logging.getLogger('wally')
52 logger.setLevel(logging.DEBUG)
53 sh = logging.StreamHandler()
54 sh.setLevel(def_level)
55
56 log_format = '%(asctime)s - %(levelname)s - %(name)-15s - %(message)s'
57 colored_formatter = ColoredFormatter(log_format, datefmt="%H:%M:%S")
58
59 sh.setFormatter(colored_formatter)
60 logger.addHandler(sh)
61
62 logger_api = logging.getLogger("wally.fuel_api")
63
64 if log_fname is not None:
65 fh = logging.FileHandler(log_fname)
66 log_format = '%(asctime)s - %(levelname)8s - %(name)-15s - %(message)s'
67 formatter = logging.Formatter(log_format, datefmt="%H:%M:%S")
68 fh.setFormatter(formatter)
69 fh.setLevel(logging.DEBUG)
70 logger.addHandler(fh)
71 logger_api.addHandler(fh)
72 else:
73 fh = None
74
75 logger_api.addHandler(sh)
76 logger_api.setLevel(logging.WARNING)
77
78 logger = logging.getLogger('paramiko')
79 logger.setLevel(logging.WARNING)
80 # logger.addHandler(sh)
81 if fh is not None:
82 logger.addHandler(fh)