Package logilab-common-0 :: Package 36 :: Package 1 :: Module logging_ext
[frames] | no frames]

Source Code for Module logilab-common-0.36.1.logging_ext

 1  # -*- coding: utf-8 -*- 
 2   
 3  """Extends the logging module from the standard library. 
 4   
 5  :copyright: 2000-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved. 
 6  :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr 
 7  :license: General Public License version 2 - http://www.gnu.org/licenses 
 8  """ 
 9  __docformat__ = "restructuredtext en" 
10   
11  import logging 
12   
13  from logilab.common.textutils import colorize_ansi 
14   
15 -def xxx_cyan(record):
16 if 'XXX' in record.message: 17 return 'cyan'
18
19 -class ColorFormatter(logging.Formatter):
20 """ 21 A color Formatter for the logging standard module. 22 23 By default, colorize CRITICAL and ERROR in red, WARNING in orange, INFO in 24 green and DEBUG in yellow. 25 26 self.colors is customizable via the 'color' constructor argument (dictionnary). 27 28 self.colorfilters is a list of functions that get the LogRecord 29 and return a color name or None. 30 """ 31
32 - def __init__(self, fmt=None, datefmt=None, colors=None):
33 logging.Formatter.__init__(self, fmt, datefmt) 34 self.colorfilters = [] 35 self.colors = {'CRITICAL': 'red', 36 'ERROR': 'red', 37 'WARNING': 'magenta', 38 'INFO': 'green', 39 'DEBUG': 'yellow', 40 } 41 if colors is not None: 42 assert isinstance(colors, dict) 43 self.colors.update(colors)
44
45 - def format(self, record):
46 msg = logging.Formatter.format(self, record) 47 if record.levelname in self.colors: 48 color = self.colors[record.levelname] 49 return colorize_ansi(msg, color) 50 else: 51 for cf in self.colorfilters: 52 color = cf(record) 53 if color: 54 return colorize_ansi(msg, color) 55 return msg
56
57 -def set_color_formatter(logger=None, **kw):
58 """ 59 Install a color formatter on the 'logger'. If not given, it will 60 defaults to the default logger. 61 62 Any additional keyword will be passed as-is to the ColorFormatter 63 constructor. 64 """ 65 if logger is None: 66 logger = logging.getLogger() 67 if not logger.handlers: 68 logging.basicConfig() 69 format_msg = logger.handlers[0].formatter._fmt 70 fmt = ColorFormatter(format_msg, **kw) 71 fmt.colorfilters.append(xxx_cyan) 72 logger.handlers[0].setFormatter(fmt)
73