Skip to content

Instantly share code, notes, and snippets.

@hosackm
Created July 28, 2020 01:39
Show Gist options
  • Save hosackm/654d64760e979280e6fb431af999f489 to your computer and use it in GitHub Desktop.
Save hosackm/654d64760e979280e6fb431af999f489 to your computer and use it in GitHub Desktop.
Colored logger module using Colorama
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()
@hosackm
Copy link
Author

hosackm commented Jul 28, 2020

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.

@zffocussss
Copy link

good job

@emrementese
Copy link

nice work !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment