-
-
Save channprj/831bf1135e783b3f7302037c528f1f71 to your computer and use it in GitHub Desktop.
colored python logging. And add a level 'success'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Color(object): | |
""" | |
utility to return ansi colored text. | |
""" | |
colors = { | |
'black': 30, | |
'red': 31, | |
'green': 32, | |
'yellow': 33, | |
'blue': 34, | |
'magenta': 35, | |
'cyan': 36, | |
'white': 37, | |
'bgred': 41, | |
'bggrey': 100 | |
} | |
prefix = '\033[' | |
suffix = '\033[0m' | |
def colored(self, text, color=None): | |
if color not in self.colors: | |
color = 'white' | |
clr = self.colors[color] | |
return (self.prefix+'%dm%s'+self.suffix) % (clr, text) | |
colored = Color().colored | |
import logging | |
from logging import Formatter, getLogger, StreamHandler | |
class ColoredFormatter(Formatter): | |
def format(self, record): | |
message = record.getMessage() | |
mapping = { | |
'INFO': 'cyan', | |
'WARNING': 'yellow', | |
'ERROR': 'red', | |
'CRITICAL': 'bgred', | |
'DEBUG': 'bggrey', | |
'SUCCESS': 'green' | |
} | |
clr = mapping.get(record.levelname, 'white') | |
return colored(record.levelname, clr) + ': ' + message | |
logger = logging.getLogger(__name__) | |
handler = StreamHandler() | |
formatter = ColoredFormatter() | |
handler.setFormatter(formatter) | |
logger.addHandler(handler) | |
# set success level | |
logging.SUCCESS = 25 # between WARNING and INFO | |
logging.addLevelName(logging.SUCCESS, 'SUCCESS') | |
setattr(logger, 'success', lambda message, *args: logger._log(logging.SUCCESS, message, args)) | |
if __name__ == '__main__': | |
logger.setLevel(logging.DEBUG) | |
logger.info('info') | |
logger.success('success') | |
logger.debug('debug') | |
logger.warning('warning') | |
logger.error('error') | |
logger.critical('critical') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment