Skip to content

Instantly share code, notes, and snippets.

@joshbode
Last active January 15, 2024 13:39
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joshbode/58fac7ababc700f51e2a9ecdebe563ad to your computer and use it in GitHub Desktop.
Save joshbode/58fac7ababc700f51e2a9ecdebe563ad to your computer and use it in GitHub Desktop.
Colour Logging - Works in Jupyter Lab/Notebook
import sys
import logging
from typing import Optional, Dict
from colorama import Fore, Back, Style
class ColoredFormatter(logging.Formatter):
"""Colored log formatter."""
def __init__(self, *args, colors: Optional[Dict[str, str]]=None, **kwargs) -> None:
"""Initialize the formatter with specified format strings."""
super().__init__(*args, **kwargs)
self.colors = colors if colors else {}
def format(self, record) -> str:
"""Format the specified record as text."""
record.color = self.colors.get(record.levelname, '')
record.reset = Style.RESET_ALL
return super().format(record)
formatter = ColoredFormatter(
'{asctime} |{color} {levelname:8} {reset}| {name} | {message}',
style='{', datefmt='%Y-%m-%d %H:%M:%S',
colors={
'DEBUG': Fore.CYAN,
'INFO': Fore.GREEN,
'WARNING': Fore.YELLOW,
'ERROR': Fore.RED,
'CRITICAL': Fore.RED + Back.WHITE + Style.BRIGHT,
}
)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger = logging.getLogger()
logger.handlers[:] = []
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
@mjayee
Copy link

mjayee commented Jan 3, 2020

Works very well in Jupyter Lab. Thank you for sharing!

@tonybeggs
Copy link

This is really excellent. Thanks for sharing

@daigz1224
Copy link

Thanks for sharing! I slightly change the formatter to condense the output:

formatter = ColoredFormatter(
    '{color}[{levelname:.1s}] {message}{reset}',
    style='{', datefmt='%Y-%m-%d %H:%M:%S',
    colors={
        'DEBUG': Fore.CYAN,
        'INFO': Fore.GREEN,
        'WARNING': Fore.YELLOW,
        'ERROR': Fore.RED,
        'CRITICAL': Fore.RED + Back.WHITE + Style.BRIGHT,
    }
)

image

@monocongo
Copy link

I appreciate you sharing this @joshbode , thanks also to @daigz1224 for the compact alternative.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment