Skip to content

Instantly share code, notes, and snippets.

@slank
Created November 4, 2022 22:00
Show Gist options
  • Save slank/d2ac95c11d0a98704cdca6e57c3423b0 to your computer and use it in GitHub Desktop.
Save slank/d2ac95c11d0a98704cdca6e57c3423b0 to your computer and use it in GitHub Desktop.
Python color multiline log formatter with example logger setup
import logging
import os
# DEFAULT_FMT = "(%(filename)s:%(lineno)d) %(message)s"
DEFAULT_FMT = "%(message)s"
class ColorMultilineLogFormatter(logging.Formatter):
grey = "\x1b[37m"
bold_grey = "\x1b[37;1m"
blue = "\x1b[34;1m"
yellow = "\x1b[33m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
@classmethod
def format_levelname(cls, levelno, levelname):
color = {
logging.INFO: cls.blue,
logging.WARNING: cls.yellow,
logging.ERROR: cls.red,
logging.CRITICAL: cls.bold_red,
}.get(levelno, cls.grey)
return "[" + color + levelname + cls.reset + "]"
def format(self, record):
morelines = []
if "\n" in record.msg:
record.msg, *morelines = record.msg.splitlines()
message = super().format(record) # additional lines do not have token substitution
prefix = self.format_levelname(record.levelno, record.levelname)
output = prefix + " " + message
for line in morelines:
output += "\n... " + line
return output
def setupLogging(format=DEFAULT_FMT):
log_level = logging.INFO
if os.getenv("DEBUG"):
log_level = logging.DEBUG
root = logging.getLogger()
root.setLevel(log_level)
handler = logging.StreamHandler()
handler.setFormatter(ColorLogFormatter(format))
root.addHandler(handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment