Skip to content

Instantly share code, notes, and snippets.

@scotthaleen
Last active January 8, 2024 14:46
Show Gist options
  • Save scotthaleen/24d7aca0a826460ef7ccfe96c2dfe8c7 to your computer and use it in GitHub Desktop.
Save scotthaleen/24d7aca0a826460ef7ccfe96c2dfe8c7 to your computer and use it in GitHub Desktop.
Color Logging in Python 3.8

Install

pip install colorama pyyaml

Example

output

---
version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(message)s"
color:
format: "%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(message)s"
(): __main__.ColoredFormatter
use_color: true
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: color
stream: ext://sys.stdout
info_file_handler:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: simple
filename: tapp.log
maxBytes: 20971520 # 20MB
backupCount: 20
encoding: utf8
error_file_handler:
class: logging.handlers.RotatingFileHandler
level: ERROR
formatter: simple
filename: terrors.log
maxBytes: 10485760 # 100MB
backupCount: 20
encoding: utf8
root:
level: DEBUG
handlers: [console, info_file_handler, error_file_handler]
import logging
import logging.config
import os
from logging import Logger
import colorama
import yaml
from colorama import Back, Fore, Style
COLORS = {
"WARNING": Fore.YELLOW,
"INFO": Fore.CYAN,
"DEBUG": Fore.BLUE,
"CRITICAL": Fore.YELLOW,
"ERROR": Fore.RED,
}
class ColoredFormatter(logging.Formatter):
def __init__(self, *, format, use_color):
logging.Formatter.__init__(self, fmt=format)
self.use_color = use_color
def format(self, record):
msg = super().format(record)
if self.use_color:
levelname = record.levelname
if hasattr(record, "color"):
return f"{record.color}{msg}{Style.RESET_ALL}"
if levelname in COLORS:
return f"{COLORS[levelname]}{msg}{Style.RESET_ALL}"
return msg
with open("logging.yaml", "rt") as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
logger: Logger = logging.getLogger(__name__)
logger.info("Test INFO", extra={"color": Back.RED})
logger.info("Test INFO", extra={"color": f"{Style.BRIGHT}{Back.RED}"})
logger.info("Test INFO")
logger.debug("Test DEBUG")
logger.warning("Test WARN")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment