Last active
April 21, 2020 08:48
-
-
Save wheresjames/cf81525bc05e3d7879c1e7e966ebdab4 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
# Python 3 print function | |
from __future__ import print_function | |
from inspect import stack, getframeinfo | |
import os | |
import sys | |
import inspect | |
import functools | |
import traceback | |
class Logging: | |
def __init__(self): | |
self.console_colors = { | |
'BLACK' : '\033[90m', | |
'RED' : '\033[91m', | |
'GREEN' : '\033[92m', | |
'YELLOW' : '\033[93m', | |
'BLUE' : '\033[94m', | |
'MAGENTA' : '\033[95m', | |
'CYAN' : '\033[96m', | |
'WHITE' : '\033[97m', | |
'BOLD' : '\033[1m', | |
'FAINT' : '\033[2m', | |
'ITALIC' : '\033[3m', | |
'UNDERLINE' : '\033[4m', | |
'BLINK' : '\033[5m', | |
'NEGATIVE' : '\033[7m', | |
'STRIKEOUT' : '\033[9m', | |
'DEFAULT' : '\033[0m' | |
} | |
self.console_color_filters = {} | |
def addLogFilter(self, f): | |
p = f.split(':') | |
if 1 < len(p): | |
self.console_color_filters[p[0]] = p[1:] | |
def addLogFilters(self, f): | |
p = f.split(',') | |
if p: | |
for v in p: | |
self.addLogFilter(v) | |
def getLogFilters(self): | |
return self.console_color_filters | |
def __call__(self, *args): | |
def formatStr(s): | |
if isinstance(s, Exception): | |
return str(" !!! EXCEPTION !!!\n" + traceback.format_exc()) | |
return str(s) | |
# Concat args | |
if 1 >= len(args): | |
s = formatStr(*args) | |
else: | |
s = functools.reduce(lambda x ,y : formatStr(x) + ' ' + formatStr(y), args) | |
# Show file/function/line | |
fi = inspect.getframeinfo(inspect.stack()[1][0]) | |
s = os.path.basename(fi.filename) + ":" + fi.function + "(" + str(fi.lineno) + "): " + str(s) | |
# Apply color filters | |
beg = '' | |
end = '' | |
try: | |
for k,v in self.console_color_filters.items(): | |
if 0 <= s.lower().find(k.lower()): | |
end = self.console_colors['DEFAULT'] | |
for c in v: | |
c = c.upper() | |
if 'BLOCK' == c: | |
return | |
elif c in self.console_colors: | |
beg += self.console_colors[c] | |
except Exception as e: | |
print(e) | |
beg = '' | |
end = '' | |
print(beg + s + end) | |
sys.stdout.flush() | |
def showStatus(s, max=70): | |
print("\r" + s.ljust(max, ' '), end='') | |
sys.stdout.flush() | |
Log = Logging() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment