Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Python colored logging with crayons
import logging
import crayons
# Define logging colors here
LOGGING_STYLES = {
'debug': {'color': 'white', 'bold': False},
'info': {'color': 'green', 'bold': True},
'warning': {'color': 'magenta', 'bold': True},
'error': {'color': 'yellow', 'bold': True},
'critical': {'color': 'red', 'bold': True},
'exception': {'color': 'cyan', 'bold': False},
}
def colored_logger(logger):
"""Make logging colorful"""
try:
if logger.colored:
return logger
except AttributeError:
def _colored_logging_func(logging_func, color, bold):
def wrapper_logging_func(msg, *args, **kwargs):
logging_func(getattr(crayons, color)(msg, bold=bold),
*args, **kwargs)
return wrapper_logging_func
for fname, style in LOGGING_STYLES.items():
setattr(logger, fname,
_colored_logging_func(getattr(logger, fname),
style['color'],
bold=style['bold']))
logger.colored = True
return logger
# Usage example
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
logger = colored_logger(logger)
logger.debug('debug with color %s', LOGGING_STYLES['debug']['color'])
logger.info('info with color %s', LOGGING_STYLES['info']['color'])
logger.warning('warning with color %s', LOGGING_STYLES['warning']['color'])
logger.error('error with color %s', LOGGING_STYLES['error']['color'])
logger.critical('critical with color %s', LOGGING_STYLES['critical']['color'])
try:
raise Exception
except Exception:
logger.exception('exception with color %s', LOGGING_STYLES['exception']['color'])
@herrkaefer

This comment has been minimized.

Copy link
Owner Author

commented May 9, 2019

What you see:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.