Created
January 29, 2021 16:01
-
-
Save aib/4725e2ac94e620409791c7a6ebc33f31 to your computer and use it in GitHub Desktop.
Colored log formatter for Python's logging
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
import logging | |
LEVELS = { | |
logging.CRITICAL: { 'label': "CRIT ", 'style-pre': "\033[95m", 'style-post': "\033[0m" }, | |
logging.ERROR: { 'label': "ERROR", 'style-pre': "\033[91m", 'style-post': "\033[0m" }, | |
logging.WARNING: { 'label': "WARN ", 'style-pre': "\033[93m", 'style-post': "\033[0m" }, | |
logging.INFO: { 'label': "INFO ", 'style-pre': "\033[97m", 'style-post': "\033[0m" }, | |
logging.DEBUG: { 'label': "DEBUG", 'style-pre': "\033[37m", 'style-post': "\033[0m" }, | |
logging.NOTSET: { 'label': " ", 'style-pre': "\033[90m", 'style-post': "\033[0m" }, | |
} | |
class Formatter(logging.Formatter): | |
def format(self, record): | |
level = LEVELS[max(filter(lambda lvl: record.levelno >= lvl, LEVELS))] | |
if record.exc_info: | |
exc_msg = "\n" + super().formatException(record.exc_info) | |
else: | |
exc_msg = "" | |
super().format(record) | |
return "%s%s [%s] [%s] %s%s%s" % ( | |
level['style-pre'], | |
super().formatTime(record), | |
level['label'], | |
record.name, | |
record.message, | |
exc_msg, | |
level['style-post'] | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment