Skip to content

Instantly share code, notes, and snippets.

@cdmatta
Created November 3, 2024 10:47
Show Gist options
  • Save cdmatta/ad985af9e33449da34a832d4c4b37f26 to your computer and use it in GitHub Desktop.
Save cdmatta/ad985af9e33449da34a832d4c4b37f26 to your computer and use it in GitHub Desktop.
Python3 color log output with no additional packages
import logging
date_format = "%Y-%m-%dT%H:%M:%S"
log_format = "%(asctime)s.%(msecs)03d %(levelname)s %(message)s"
class LogFormatter(logging.Formatter):
white = "\x1b[37;20m"
blue = "\x1b[34;20m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
FORMATS = {
logging.DEBUG: white + log_format + reset,
logging.INFO: blue + log_format + reset,
logging.WARNING: yellow + log_format + reset,
logging.ERROR: red + log_format + reset,
logging.CRITICAL: bold_red + log_format + reset,
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt, date_format)
return formatter.format(record)
def setup_logger(verbose: bool, color: bool):
log_level = logging.DEBUG if verbose else logging.INFO
if color:
ch = logging.StreamHandler()
ch.setFormatter(LogFormatter())
logging.basicConfig(level=log_level, handlers=[ch])
return
logging.basicConfig(level=log_level, format=log_format, datefmt=date_format)
import logging
from .log_util import setup_logger
def main():
setup_logger(True, True)
log = logging.getLogger(__name__)
log.debug("debug message")
log.info("info message")
log.warning("warning message")
log.error("error message")
log.critical("critical message")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment