Created
August 16, 2020 04:17
-
-
Save lamchau/b72af3a22f2d284e9fc8b9c6432f4269 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
#!/usr/bin/env python3 | |
import collections | |
import logging | |
import sys | |
import os | |
class ColorizedStreamHandler(logging.StreamHandler): | |
def __init__(self): | |
super().__init__() | |
# we define color here for custom color palettes per instance | |
Color = collections.namedtuple('Color', [ | |
'BLACK', 'RED', 'GREEN', 'YELLOW', | |
'BLUE', 'MAGENTA', 'CYAN', 'WHITE', | |
'BLACK_BOLD', 'RED_BOLD', 'GREEN_BOLD', 'YELLOW_BOLD', | |
'BLUE_BOLD', 'MAGENTA_BOLD', 'CYAN_BOLD', 'WHITE_BOLD']) | |
# octal ansi color values (0, 255) | |
self.ForegroundColor = Color(*map(lambda x: f'\33[38;5;{x}m', range(16))) | |
self.BackgroundColor = Color(*map(lambda x: f'\33[48;5;{x}m', range(16))) | |
self.RESET = '\33[0m' | |
self.LOG_LEVEL = { | |
logging.CRITICAL: (self.BackgroundColor.RED_BOLD + self.ForegroundColor.WHITE_BOLD), | |
logging.ERROR: self.ForegroundColor.RED_BOLD, | |
logging.WARNING: self.ForegroundColor.YELLOW_BOLD, | |
logging.INFO: self.ForegroundColor.BLUE_BOLD, | |
logging.DEBUG: self.RESET, | |
logging.NOTSET: self.RESET | |
} | |
def emit(self, record): | |
try: | |
message = self.format(record) | |
if ColorizedStreamHandler.supports_color(): | |
color = self.LOG_LEVEL.get(record.levelno) | |
message = f'{color}{message}{self.RESET}' | |
self.stream.write(message) | |
self.stream.write(self.terminator) | |
self.flush() | |
except (KeyboardInterrupt, SystemExit): | |
raise | |
except (Exception): | |
self.handleError(record) | |
@staticmethod | |
def supports_color(): | |
''' | |
Returns True if the running system's terminal supports color, and False | |
otherwise. | |
Extracted from Django: https://git.io/JJ7zX | |
''' | |
supported_platform = sys.platform != 'win32' or 'ANSICON' in os.environ | |
# isatty is not always implemented, #6223. | |
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() | |
return supported_platform and is_a_tty | |
def color_test(self): | |
print(f'{"-" * 10} PALETTE TEST {"-" * 10}') | |
ForegroundColor = self.ForegroundColor | |
BackgroundColor = self.BackgroundColor | |
columns = zip(zip(ForegroundColor._fields, ForegroundColor), | |
zip(BackgroundColor._fields, BackgroundColor)) | |
for left, right in columns: | |
left = f'{left[1]}{left[0]:14}{self.RESET}' | |
right = f'{right[1]}{right[0]:14}{self.RESET}' | |
print(f' {left}{right}{self.RESET}') | |
if __name__ == '__main__': | |
logger = logging.getLogger(__name__) | |
colorizer = ColorizedStreamHandler() | |
colorizer.setFormatter(logging.Formatter( | |
fmt='%(asctime)s.%(msecs)03d [%(levelname)8s] - %(message)s', | |
datefmt='%Y-%m-%d %H:%M:%S')) | |
colorizer.setLevel(logging.DEBUG) | |
logger.addHandler(colorizer) | |
logger.setLevel(logging.DEBUG) | |
colorizer.color_test() | |
for level in colorizer.LOG_LEVEL: | |
logger.log(level, f'logging example for {level}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment