Skip to content

Using Jupyter

Colorized Logging

Setup awesome colorized logging by adding the following code to the root folder of your project. Call it something like colorized_logging.py (reference https://gist.github.com/joshbode/58fac7ababc700f51e2a9ecdebe563ad).

python
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)
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)

Next, in your Jupyter notebook, import this file, along with the logging library.

python
import color_logging
from logging import      \
    info    as loginfo,  \
    debug   as logdebug, \
    warning as logwarn,  \
    error   as logerror
import color_logging
from logging import      \
    info    as loginfo,  \
    debug   as logdebug, \
    warning as logwarn,  \
    error   as logerror

ADDITIONAL RESOURCES