Created
June 6, 2013 20:34
-
-
Save florentx/5724696 to your computer and use it in GitHub Desktop.
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 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