Last active
May 18, 2019 00:14
-
-
Save herrkaefer/3582e2ab5a344647e325782e1a1f3c84 to your computer and use it in GitHub Desktop.
Simple Python colored logging with crayons
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 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']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What you see: