-
-
Save mameen/c129d7af87fdbaf4a9836d0e84588cb3 to your computer and use it in GitHub Desktop.
Colorizing log handler
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
# Original code from https://gist.github.com/kergoth/813057 | |
# Courtesy http://plumberjack.blogspot.com/2010/12/colorizing-logging-output-in-terminals.html | |
# Tweaked to use colorama for the coloring | |
import colorama | |
import logging | |
import os | |
import sys | |
class ColorizingStreamHandler(logging.StreamHandler): | |
color_map = { | |
logging.DEBUG: colorama.Style.DIM + colorama.Fore.CYAN, | |
logging.WARNING: colorama.Fore.LIGHTYELLOW_EX, | |
logging.ERROR: colorama.Fore.RED, | |
logging.CRITICAL: colorama.Back.RED, | |
logging.INFO: colorama.Style.DIM + colorama.Fore.YELLOW, | |
} | |
def __init__(self, stream, color_map=None): | |
logging.StreamHandler.__init__(self, | |
colorama.AnsiToWin32(stream).stream) | |
if color_map is not None: | |
self.color_map = color_map | |
@property | |
def is_tty(self): | |
isatty = getattr(self.stream, 'isatty', None) | |
return isatty and isatty() | |
def format(self, record): | |
message = logging.StreamHandler.format(self, record) | |
if self.is_tty: | |
# Don't colorize a traceback | |
parts = message.split('\n', 1) | |
parts[0] = self.colorize(parts[0], record) | |
message = '\n'.join(parts) | |
return message | |
def colorize(self, message, record): | |
try: | |
return (self.color_map[record.levelno] + message + | |
colorama.Style.RESET_ALL) | |
except KeyError: | |
return message | |
@staticmethod | |
def LoadColorLog(log_file=None, level=logging.INFO): | |
colorama.init(autoreset=True) | |
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") | |
rootLogger = logging.getLogger() | |
rootLogger.setLevel(level) | |
if log_file is not None: | |
if os.path.exists(log_file): | |
os.remove(log_file) | |
fileHandler = logging.FileHandler(log_file) | |
fileHandler.setFormatter(logFormatter) | |
rootLogger.addHandler(fileHandler) | |
handler = ColorizingStreamHandler(sys.stdout) | |
handler.setFormatter(logFormatter) | |
rootLogger.addHandler(handler) | |
return rootLogger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment