Skip to content

Instantly share code, notes, and snippets.

@jrjhealey
Created November 15, 2017 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrjhealey/b555add717b1dd81608f51bb42427ad6 to your computer and use it in GitHub Desktop.
Save jrjhealey/b555add717b1dd81608f51bb42427ad6 to your computer and use it in GitHub Desktop.
# Getting python logging info output in a colour coded and customised manner.
# Stolen from M. Galardini and https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output/2532931#2532931
import logging
import sys
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
COLORS = {
'WARNING' : YELLOW,
'INFO' : WHITE,
'DEBUG' : WHITE,
'CRITICAL' : MAGENTA,
'ERROR' : RED,
'RED' : RED,
'GREEN' : GREEN,
'YELLOW' : YELLOW,
'BLUE' : BLUE,
'MAGENTA' : MAGENTA,
'CYAN' : CYAN,
'WHITE' : WHITE,
}
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"
class ColorFormatter(logging.Formatter):
def __init__(self, *args, **kwargs):
logging.Formatter.__init__(self, *args, **kwargs)
if not hasattr(sys.stdout, 'isatty') or not sys.stdout.isatty():
self.use_it = False
else:
self.use_it = True
def format(self, record):
if not self.use_it:
message = logging.Formatter.format(self, record)
message = message.replace("$RESET", '')\
.replace("$BOLD", '')\
.replace("$COLOR", '')
return message
levelname = record.levelname
color = COLOR_SEQ % (30 + COLORS[levelname])
message = logging.Formatter.format(self, record)
message = message.replace("$RESET", RESET_SEQ)\
.replace("$BOLD", BOLD_SEQ)\
.replace("$COLOR", color)
for k,v in COLORS.items():
message = message.replace("$" + k, COLOR_SEQ % (v+30))\
.replace("$BG" + k, COLOR_SEQ % (v+40))\
.replace("$BG-" + k, COLOR_SEQ % (v+40))
return message + RESET_SEQ
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = ColorFormatter('%(asctime)s - $COLOR%(message)s$RESET','%H:%M:%S')
ch.setFormatter(formatter)
logger.addHandler(ch)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment