1# -*- coding: utf-8 -*- 2 3# Copyright(C) 2010-2011 Romain Bignon 4# 5# This file is part of weboob. 6# 7# weboob is free software: you can redistribute it and/or modify 8# it under the terms of the GNU Lesser General Public License as published by 9# the Free Software Foundation, either version 3 of the License, or 10# (at your option) any later version. 11# 12# weboob is distributed in the hope that it will be useful, 13# but WITHOUT ANY WARRANTY; without even the implied warranty of 14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15# GNU Lesser General Public License for more details. 16# 17# You should have received a copy of the GNU Lesser General Public License 18# along with weboob. If not, see <http://www.gnu.org/licenses/>. 19 20from __future__ import print_function 21 22import sys 23from collections import defaultdict 24from logging import addLevelName, Formatter, getLogger as _getLogger, LoggerAdapter 25 26__all__ = ['getLogger', 'createColoredFormatter', 'settings'] 27 28 29RESET_SEQ = "\033[0m" 30COLOR_SEQ = "%s%%s" + RESET_SEQ 31 32COLORS = { 33 'DEBUG': COLOR_SEQ % "\033[0;36m", 34 'INFO': COLOR_SEQ % "\033[32m", 35 'WARNING': COLOR_SEQ % "\033[1;33m", 36 'ERROR': COLOR_SEQ % "\033[1;31m", 37 'CRITICAL': COLOR_SEQ % ("\033[1;33m\033[1;41m"), 38 'DEBUG_FILTERS': COLOR_SEQ % "\033[0;35m", 39} 40 41DEBUG_FILTERS = 8 42addLevelName(DEBUG_FILTERS, 'DEBUG_FILTERS') 43 44 45# Global settings f logger. 46settings = defaultdict(lambda: None) 47 48 49def getLogger(name, parent=None): 50 if isinstance(parent, LoggerAdapter): 51 klass = type(parent) 52 extra = parent.extra 53 parent = parent.logger 54 else: 55 klass = None 56 extra = None 57 58 if parent: 59 name = parent.name + '.' + name 60 logger = _getLogger(name) 61 logger.settings = settings 62 63 if extra: 64 logger = klass(logger, extra) 65 logger.settings = settings 66 return logger 67 68 69class ColoredFormatter(Formatter): 70 """ 71 Class written by airmind: 72 http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored 73 """ 74 75 def format(self, record): 76 levelname = record.levelname 77 msg = Formatter.format(self, record) 78 if levelname in COLORS: 79 msg = COLORS[levelname] % msg 80 return msg 81 82 83def createColoredFormatter(stream, format): 84 if (sys.platform != 'win32') and stream.isatty(): 85 return ColoredFormatter(format) 86 else: 87 return Formatter(format) 88 89 90if __name__ == '__main__': 91 for levelname, cs in COLORS.items(): 92 print(cs % levelname, end=' ') 93