We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Sometimes, you just want to color the output of the logging package in Python.
Here's a simple custom formatter which shows how this can be done:
import logging
class ColorFormatter(logging.Formatter):
"""Logging Formatter to add colors and count warning / errors"""
grey = "\x1b[90m"
green = "\x1b[92m"
yellow = "\x1b[93m"
red = "\x1b[91m"
reset = "\x1b[0m"
format = "%(asctime)s | %(levelname)-5.5s | %(message)s"
FORMATS = {
logging.DEBUG: grey + format + reset,
logging.INFO: green + format + reset,
logging.WARNING: yellow + format + reset,
logging.ERROR: red + format + reset,
logging.CRITICAL: red + format + reset
}
def format(self, record):
record.levelname = 'WARN' if record.levelname == 'WARNING' else record.levelname
record.levelname = 'ERROR' if record.levelname == 'CRITICAL' else record.levelname
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)
def configure_logging():
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(ColorFormatter())
logger.addHandler(ch)
def main():
configure_logging()
logging.debug("debug message")
logging.info("info message")
logging.warning("warning message")
logging.error("error message")
logging.critical("critical message")
if __name__ == "__main__":
main()
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.