Package tipy :: Module lg
[hide private]
[frames] | no frames]

Source Code for Module tipy.lg

 1  #!/usr/bin/env python3 
 2  # -*- coding: utf-8 -*- 
 3   
 4  """A class to format the log messages + the logger instance.""" 
 5   
 6  from logging import Formatter, StreamHandler, getLogger, DEBUG 
 7   
 8   
 9  CNRM = '\x1B[0m' 
10  CBLK = '\x1B[30m' 
11  CRED = '\x1B[31m' 
12  CGRN = '\x1B[32m' 
13  CYEL = '\x1B[33m' 
14  CBLU = '\x1B[34m' 
15  CMAG = '\x1B[35m' 
16  CCYN = '\x1B[36m' 
17  CWHT = '\x1B[37m' 
18  BNRM = '\x1B[1m\x1b[00m' 
19  BBLK = '\x1B[1m\x1b[30m' 
20  BRED = '\x1B[1m\x1b[31m' 
21  BGRN = '\x1B[1m\x1b[32m' 
22  BYEL = '\x1B[1m\x1b[33m' 
23  BBLU = '\x1B[1m\x1b[34m' 
24  BMAG = '\x1B[1m\x1b[35m' 
25  BCYN = '\x1B[1m\x1b[36m' 
26  BWHT = '\x1B[1m\x1b[37m' 
27  BOLD = '\x1B[1m' 
28   
29   
30 -class ColorFormatter(Formatter):
31 """Add color to log messages by overring logging.Formater methods.""" 32 33 FORMAT = ("[$BOLD%(filename)-8s: " 34 "%(funcName)20s():%(lineno)4s$RESET][%(levelname)-18s] " 35 "%(message)s ") 36 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) 37 38 COLOR_SEQ = "\x1B[%dm" 39 40 COLORS = { 41 'WARNING': YELLOW, 42 'INFO': WHITE, 43 'DEBUG': BLUE, 44 'CRITICAL': YELLOW, 45 'ERROR': RED 46 } 47
48 - def __init__(self, use_color=True):
49 msg = self.formatter_msg(self.FORMAT, use_color) 50 Formatter.__init__(self, msg) 51 self.use_color = use_color
52
53 - def formatter_msg(self, msg, use_color=True):
54 if use_color: 55 msg = msg.replace("$RESET", CNRM) 56 msg = msg.replace("$BOLD", BOLD) 57 else: 58 msg = msg.replace("$RESET", "") 59 msg = msg.replace("$BOLD", "") 60 return msg
61
62 - def format(self, record):
63 levelname = record.levelname 64 if self.use_color and levelname in self.COLORS: 65 fore_color = 30 + self.COLORS[levelname] 66 levelname_color = self.COLOR_SEQ % fore_color + levelname + CNRM 67 record.levelname = levelname_color 68 return Formatter.format(self, record)
69 70 71 CF = ColorFormatter() 72 handler = StreamHandler() 73 handler.setFormatter(CF) 74 #: The logger which can be used anywhere in the program 75 lg = getLogger('root') 76 lg.setLevel(DEBUG) 77 lg.addHandler(handler) 78