Skip to content

Instantly share code, notes, and snippets.

@antoinedelia
Last active November 9, 2021 08:24
Show Gist options
  • Save antoinedelia/058b839965ab61491638a26aab957bc2 to your computer and use it in GitHub Desktop.
Save antoinedelia/058b839965ab61491638a26aab957bc2 to your computer and use it in GitHub Desktop.
Basic logger class with color and log to file
import logging
import os
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
LOG_FILE_NAME = os.getenv("LOG_FILE_NAME", "log.txt")
class Color:
"""An enum for the different colors available for printing
"""
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 Logger:
def __init__(self, name: str, log_level: str = LOG_LEVEL, use_color: bool = False):
self.name = name
self.log_level = logging.getLevelName(LOG_LEVEL)
logging.basicConfig(
handlers=[
logging.FileHandler(LOG_FILE_NAME, "a"),
logging.StreamHandler()
],
format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s",
datefmt="%H:%M:%S",
level=logging.DEBUG
)
self.logger = logging.getLogger(name)
self.logger.setLevel(log_level)
self.use_color = use_color
def info(self, message):
self.logger.info(message)
def warning(self, message):
warning_message = f"{Color.YELLOW} {str(message)} {Color.END}" if self.use_color else str(message)
self.logger.warning(warning_message)
def debug(self, message):
self.logger.debug(message)
def error(self, message):
error_message = f"{Color.RED} {str(message)} {Color.END}" if self.use_color else str(message)
self.logger.error(error_message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment