Created
April 7, 2018 12:39
-
-
Save rhymes/94a445458159df3614d816f0c587eee6 to your computer and use it in GitHub Desktop.
Structlog key value renderer with colors
This file contains hidden or 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
# coding: utf-8 | |
'Color key value renderer' | |
import itertools | |
from io import StringIO | |
import colorama | |
import structlog | |
LEVEL_COLORS = { | |
'critical': colorama.Fore.RED, | |
'exception': colorama.Fore.RED, | |
'error': colorama.Fore.RED, | |
'warn': colorama.Fore.YELLOW, | |
'warning': colorama.Fore.YELLOW, | |
'info': colorama.Fore.GREEN, | |
'debug': colorama.Fore.BLUE, | |
'notset': colorama.Back.RED, | |
} | |
COLORS = { | |
'timestamp': colorama.Style.DIM, | |
'time': colorama.Style.DIM, | |
'event': colorama.Fore.BLUE + colorama.Style.BRIGHT | |
} | |
# all ANSI colors, except black, white and cyan | |
KV_COLORS = ( | |
colorama.Fore.RED, colorama.Fore.GREEN, colorama.Fore.YELLOW, | |
colorama.Fore.BLUE, colorama.Fore.MAGENTA | |
) | |
def _color(key, colors): | |
return COLORS.get(key, next(colors)) | |
class ColorKeyValueRenderer(structlog.processors.KeyValueRenderer): | |
'Renderer to output key values with colors' | |
def __init__(self, force_colors=False, **kwargs): | |
super().__init__(self, **kwargs) | |
if force_colors: | |
colorama.deinit() | |
colorama.init(strip=False) | |
else: | |
colorama.init() | |
def __call__(self, _, __, event_dict): | |
colors_iterator = itertools.cycle(reversed(KV_COLORS)) | |
buffer = StringIO() | |
for key, value in self._ordered_items(event_dict): | |
if value is not None: | |
if key == 'level': | |
buffer.write( | |
LEVEL_COLORS[value] + key + '=' + str(value) + | |
colorama.Style.RESET_ALL + ' ' | |
) | |
else: | |
buffer.write( | |
_color(key, colors_iterator) + key + '=' + | |
self._repr(value) + colorama.Style.RESET_ALL + ' ' | |
) | |
return buffer.getvalue() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment