import logging
import sys
from typing import Optional
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
# ANSI color codes
_DEFAULT = "\033[0m"
_RESET_COLOR = "\033[0m"
_BUE = "\033[94m"
_RED = "\033[91m"
_YELLOW = "\033[93m"
_MAGENTA = "\033[95m"
_COLOR_MAP = {
logging.DEBUG: _BUE,
logging.INFO: _DEFAULT,
logging.WARNING: _YELLOW,
logging.ERROR: _RED,
logging.CRITICAL: _MAGENTA,
}
class ColorFormatter(logging.Formatter):
"""Formatter that colors the log messages based on level."""
def format(self, record: logging.LogRecord) -> str:
message = super().format(record)
color = _COLOR_MAP.get(record.levelno, _RESET_COLOR)
return f"{color}{message}{_RESET_COLOR}"
def setup_logger(name: str = None, level: Optional[int] = logging.INFO) -> logging.Logger:
"""Configure a logger that outputs to the console with colored messages."""
logger = logging.getLogger(name)
logger.setLevel(level)
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(level)
handler.setFormatter(ColorFormatter(LOG_FORMAT))
logger.addHandler(handler)
logger.propagate = False
return logger
logger = setup_logger("my_logger", logging.DEBUG)
logger.debug("Debug message")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")
logger.critical("Critical message")
To embed this project on your website, copy the following code and paste it into your website's HTML: