Created
November 4, 2022 22:00
-
-
Save slank/d2ac95c11d0a98704cdca6e57c3423b0 to your computer and use it in GitHub Desktop.
Python color multiline log formatter with example logger setup
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
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