Last active
September 12, 2024 05:38
-
-
Save joshbode/58fac7ababc700f51e2a9ecdebe563ad to your computer and use it in GitHub Desktop.
Colour Logging - Works in Jupyter Lab/Notebook
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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I appreciate you sharing this @joshbode , thanks also to @daigz1224 for the compact alternative.