Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import logging
class ColoredFormatter(logging.Formatter):
def __init__(self, fmt, datefmt=None):
logging.Formatter.__init__(self, fmt, datefmt)
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(30, 38)
self.COLORS = dict(
DEBUG=GREEN, INFO=WHITE, WARNING=YELLOW, ERROR=RED, CRITICAL=MAGENTA
)
def format(self, record):
color = self.COLORS[record.levelname]
msg = logging.Formatter.format(self, record)
return f"\033[1;{color}m{msg}\033[0m"
class ColoredLogger(logging.Logger):
def __init__(self, name):
logging.Logger.__init__(self, name, logging.DEBUG)
FORMAT = "%(asctime)s %(filename)s:%(lineno)-4d %(levelname).1s %(message)s"
DATEFMT = "%Y-%m-%d %H:%M:%S"
color_formatter = ColoredFormatter(FORMAT, DATEFMT)
console = logging.StreamHandler()
console.setFormatter(color_formatter)
self.addHandler(console)
logging.setLoggerClass(ColoredLogger)
if __name__ == "__main__":
log = logging.getLogger(__name__)
log.debug("test")
log.info("test")
log.warning("test")
log.error("test")
log.critical("test")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.