Created
April 21, 2019 22:49
-
-
Save jlumbroso/0181339f0b65dff76ca82188579ce12e to your computer and use it in GitHub Desktop.
Short snippet showing how to have colored terminal logging output in Python.
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 os | |
import logging | |
class _Color: | |
PURPLE = '\033[95m' | |
CYAN = '\033[96m' | |
DARKCYAN = '\033[36m' | |
BLUE = '\033[94m' | |
GREEN = '\033[92m' | |
YELLOW = '\033[93m' | |
RED = '\033[91m' | |
BOLD = '\033[1m' | |
UNDERLINE = '\033[4m' | |
END = '\033[0m' | |
class SimpleColorFormatter(logging.Formatter): | |
_title = { | |
"DEBUG": "{END}[{BOLD}DBUG{END}]{END}".format(**_Color.__dict__), | |
"INFO": "{END}[{BOLD}{GREEN}INFO{END}]{END}".format(**_Color.__dict__), | |
"ERROR": "{END}[{BOLD}{RED}ERR {END}]{END}".format(**_Color.__dict__), | |
"WARNING": "{END}[{BOLD}{BLUE}WARN{END}]{END}".format(**_Color.__dict__) | |
} | |
def normalizePath(self, path): | |
abs_path = os.path.abspath(path) | |
pwd_path = os.getcwd() | |
return abs_path.replace(pwd_path, ".", 1) | |
def formatMessage(self, msg: logging.LogRecord): | |
header = self._title.get(msg.levelname, self._title.get("INFO")) | |
return("{} {} (\"{}\", line {}): {}".format( | |
header, | |
msg.module, | |
self.normalizePath(msg.filename), | |
msg.lineno, | |
msg.message | |
)) | |
def setupLogging(level="DEBUG"): | |
# Add the color handler to the terminal output | |
handler = logging.StreamHandler() | |
formatter = SimpleColorFormatter() | |
handler.setFormatter(formatter) | |
# Set logging level | |
root = logging.getLogger() | |
root.setLevel(os.environ.get("LOGLEVEL", level)) | |
# Add the color handler to the logger | |
root.addHandler(handler) | |
return root | |
l = setupLogging() | |
l.debug("This is an debug.") | |
l.info("This is an info.") | |
l.warning("This is an warning.") | |
l.error("This is an error.") | |
raise ValueError("value") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment