Created
July 28, 2020 01:39
-
-
Save hosackm/654d64760e979280e6fb431af999f489 to your computer and use it in GitHub Desktop.
Colored logger module using Colorama
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
import logging | |
from colorama import init, Fore, Back | |
init(autoreset=True) | |
class ColorFormatter(logging.Formatter): | |
# Change this dictionary to suit your coloring needs! | |
COLORS = { | |
"WARNING": Fore.RED, | |
"ERROR": Fore.RED + Back.WHITE, | |
"DEBUG": Fore.BLUE, | |
"INFO": Fore.GREEN, | |
"CRITICAL": Fore.RED + Back.WHITE | |
} | |
def format(self, record): | |
color = self.COLORS.get(record.levelname, "") | |
if color: | |
record.name = color + record.name | |
record.levelname = color + record.levelname | |
record.msg = color + record.msg | |
return logging.Formatter.format(self, record) | |
class ColorLogger(logging.Logger): | |
def __init__(self, name): | |
logging.Logger.__init__(self, name, logging.DEBUG) | |
color_formatter = ColorFormatter("%(name)-10s %(levelname)-18s %(message)s") | |
console = logging.StreamHandler() | |
console.setFormatter(color_formatter) | |
self.addHandler(console) | |
def main(): | |
logging.setLoggerClass(ColorLogger) | |
logger = logging.getLogger(__name__) | |
logger.info("This is an info message") | |
logger.warning("This is a warning message") | |
logger.debug("This is a debug message") | |
logger.error("This is an error message") | |
if __name__ == "__main__": | |
main() |
good job
nice work !
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I always forget the correct order of creating loggers and stream handlers etc. when initializing a logging module in Python. This is a good copy/paste starting point for having some beautiful colored logs in your project.