Last active
August 29, 2015 14:13
-
-
Save astromechza/b712fe09f075f6bfd925 to your computer and use it in GitHub Desktop.
coloured_stream_handler.py: A logging stream handler that colours lines differently depending on their logging level.
This file contains hidden or 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
from logging import StreamHandler | |
try: | |
unicode | |
_unicode = True | |
except NameError: | |
_unicode = False | |
class ColouredStreamHandler(StreamHandler): | |
COLOURS = { | |
0: '37', # not set | |
10: '37', # debug | |
20: '39', # info | |
30: '33', # warning | |
40: '31', # error | |
50: '31;1' # critical | |
} | |
def __init__(self): | |
super(ColouredStreamHandler, self).__init__() | |
def emit(self, record): | |
try: | |
msg = self.format(record) | |
stream = self.stream | |
fs = "\033[" + self.COLOURS[record.levelno] + "m%s\033[0m\n" | |
if not _unicode: | |
stream.write(fs % msg) | |
else: | |
try: | |
if (isinstance(msg, unicode) and getattr(stream, 'encoding', None)): | |
ufs = u'%s\n' | |
try: | |
stream.write(ufs % msg) | |
except UnicodeEncodeError: | |
stream.write((ufs % msg).encode(stream.encoding)) | |
else: | |
stream.write(fs % msg) | |
except UnicodeError: | |
stream.write(fs % msg.encode("UTF-8")) | |
self.flush() | |
except (KeyboardInterrupt, SystemExit): | |
raise | |
except: | |
self.handleError(record) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment