Last active
October 13, 2016 20:57
-
-
Save inesusvet/68a9eeb8b9d2de1497edd29a3b0a4259 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
from __future__ import print_function | |
import logging | |
class ColoredFormatter(logging.Formatter): | |
""" | |
See more colors and styles at http://stackoverflow.com/a/21786287 | |
""" | |
class Colors: | |
END = '\x1b[0m' | |
BLACK = '\x1b[90m' | |
RED = '\x1b[91m' | |
GREEN = '\x1b[92m' | |
YELLOW = '\x1b[93m' | |
BLUE = '\x1b[94m' | |
PURPLE = '\x1b[95m' | |
CYAN = '\x1b[96m' | |
GRAY = '\x1b[97m' | |
class Styles: | |
BOLD = '\x1b[1m' | |
ITALIC = '\x1b[3m' | |
UNDERLINE = '\x1b[4m' | |
level_to_color = { | |
logging.ERROR: Colors.RED, | |
logging.INFO: Colors.GREEN, | |
} | |
@staticmethod | |
def wrap_level_name(fmt): | |
placeholder = '%(levelname)s' | |
head, tail = fmt.split(placeholder, 1) | |
fmt = ''.join([ | |
head, | |
'%(color_start)s', | |
placeholder, | |
'%(color_end)s', | |
tail, | |
]) | |
return fmt | |
@staticmethod | |
def wrap_line(fmt): | |
return ''.join([ | |
'%(color_start)s', | |
fmt, | |
'%(color_end)s', | |
]) | |
def __init__(self, fmt='%(message)s', **kwargs): | |
if 'levelname' in str(fmt): | |
fmt = self.wrap_level_name(fmt) | |
else: | |
fmt = self.wrap_line(fmt) | |
super(ColoredFormatter, self).__init__(fmt=fmt, **kwargs) | |
def format(self, record): | |
record.color_start = self.level_to_color.get(record.levelno, '') | |
record.color_end = self.Colors.END | |
return super(ColoredFormatter, self).format(record) | |
def main(): | |
colored_level = ColoredFormatter('%(levelname)s\t%(message)s') | |
colored_line = ColoredFormatter() | |
first_handler = logging.StreamHandler() | |
first_handler.setFormatter(colored_level) | |
second_handler = logging.StreamHandler() | |
second_handler.setFormatter(colored_line) | |
logger_class = logging.getLoggerClass() | |
logger = logger_class('') | |
logger.addHandler(first_handler) | |
logger.addHandler(second_handler) | |
logger.debug('This is low priority message, so I want it to fade out') | |
logger.info('This message says that everything goes OK') | |
logger.error('This is high priority message - it should catch my eye') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment