Skip to content

Instantly share code, notes, and snippets.

@herrkaefer
Last active May 18, 2019 00:14
Show Gist options
  • Save herrkaefer/3582e2ab5a344647e325782e1a1f3c84 to your computer and use it in GitHub Desktop.
Save herrkaefer/3582e2ab5a344647e325782e1a1f3c84 to your computer and use it in GitHub Desktop.
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
Copy link
Author

herrkaefer 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