Path: blob/develop/rootfs/usr/local/lib/web/backend/log/config.py
387 views
#!/usr/bin/env python1import sys2import logging3import logging.handlers456# The terminal has 8 colors with codes from 0 to 77BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)89# These are the sequences need to get colored ouput10RESET_SEQ = "\033[0m"11COLOR_SEQ = "\033[1;%dm"12BOLD_SEQ = "\033[1m"1314# The background is set with 40 plus the number of the color,15# and the foreground with 3016COLORS = {17'WARNING': COLOR_SEQ % (30 + YELLOW) + 'WARN ' + RESET_SEQ,18'INFO': COLOR_SEQ % (30 + WHITE) + 'INFO ' + RESET_SEQ,19'DEBUG': COLOR_SEQ % (30 + BLUE) + 'DEBUG' + RESET_SEQ,20'CRITICAL': COLOR_SEQ % (30 + YELLOW) + 'CRITI' + RESET_SEQ,21'ERROR': COLOR_SEQ % (30 + RED) + 'ERROR' + RESET_SEQ,22}232425class ColoredFormatter(logging.Formatter):26def __init__(self, msg, use_color=True):27logging.Formatter.__init__(self, msg)28self.use_color = use_color2930def format(self, record):31if self.use_color:32record.levelname = COLORS.get(record.levelname, record.levelname)33return logging.Formatter.format(self, record)343536class LoggingConfiguration(object):37COLOR_FORMAT = "%(asctime)s" + \38" %(levelname)s %(message)s " + \39"(" + BOLD_SEQ + "%(filename)s" + RESET_SEQ + ":%(lineno)d)"40NO_COLOR_FORMAT = "%(asctime)s %(levelname)s " + \41"%(message)s " + \42"(%(filename)s:%(lineno)d)"43FILE_FORMAT = "%(asctime)s %(levelname)s " + \44"%(message)s "4546@classmethod47def set(cls, log_level, log_filename, append=None, **kwargs):48""" Configure a rotating file logging49"""50logger = logging.getLogger()51logger.setLevel(log_level)5253COLOR_FORMAT = cls.COLOR_FORMAT54NO_COLOR_FORMAT = cls.NO_COLOR_FORMAT55FILE_FORMAT = cls.FILE_FORMAT56if 'name' in kwargs:57COLOR_FORMAT = COLOR_FORMAT.replace('%(threadName)-22s',58'%-22s' % (kwargs['name']))59NO_COLOR_FORMAT = NO_COLOR_FORMAT.replace(60'%(threadName)-22s', '%-22s' % (kwargs['name']))61FILE_FORMAT = FILE_FORMAT.replace(62'%(threadName)-22s', '%s' % (kwargs['name']))6364# Log to rotating file65try:66fh = logging.handlers.RotatingFileHandler(67log_filename,68mode='a+',69backupCount=370)71fh.setFormatter(ColoredFormatter(FILE_FORMAT, False))72fh.setLevel(log_level)73logger.addHandler(fh)74if not append:75# Create a new log file on every new76fh.doRollover()77except IOError as e:78print('ignore to log to {}: {}'.format(log_filename, e))7980# Log to sys.stderr using log level passed through command line81if log_level != logging.NOTSET:82log_handler = logging.StreamHandler(sys.stdout)83if sys.platform.find('linux') >= 0:84formatter = ColoredFormatter(COLOR_FORMAT)85else:86formatter = ColoredFormatter(NO_COLOR_FORMAT, False)87log_handler.setFormatter(formatter)88log_handler.setLevel(log_level)89logger.addHandler(log_handler)909192