Skip to content

Instantly share code, notes, and snippets.

@florentx
Created June 6, 2013 20:34
Show Gist options
  • Save florentx/5724696 to your computer and use it in GitHub Desktop.
Save florentx/5724696 to your computer and use it in GitHub Desktop.
import logging
import sys
import colorama
from colorama import Fore, Back, Style
LEVEL_COLOR_MAPPING = {
logging.DEBUG: Fore.BLUE + Back.RESET,
logging.INFO: Fore.GREEN + Back.RESET,
logging.WARNING: Fore.YELLOW + Back.RESET,
logging.ERROR: Fore.RED + Back.RESET,
logging.CRITICAL: Fore.WHITE + Back.RED,
}
class ColoredFormatter(logging.Formatter):
def __init__(self, fmt=None):
logging.Formatter.__init__(self, fmt)
self._fmt = self._fmt.replace('%(levelname)s', '%(coloredlevel)s')
def format(self, record):
record.coloredlevel = (LEVEL_COLOR_MAPPING.get(record.levelno, '') +
record.levelname + Style.RESET_ALL)
return logging.Formatter.format(self, record)
def init_logger(level=logging.INFO):
# Prepare the logging handler with a custom formatter
fmt = '%(asctime)s %(levelname)s %(name)s: %(message)s'
formatter = ColoredFormatter(fmt)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
# Configure the root logger
logger = logging.getLogger()
logger.addHandler(handler)
logger.setLevel(level)
# Initialize
colorama.init()
init_logger(level=logging.DEBUG)
# Examples
logger = logging.getLogger()
level_name = logging.getLevelName(logger.level)
logger.info('logger level set to %s', level_name)
logger.log(logger.level, 'logger level set to %s', level_name)
# logger.warning('...')
# logger.error('...')
# logger.critical('...')
# logger.debug('...')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment