Skip to content

Instantly share code, notes, and snippets.

@pradishb
Last active November 1, 2023 16:23
Show Gist options
  • Save pradishb/f96220129fbb0453225cddeacdf00f6c to your computer and use it in GitHub Desktop.
Save pradishb/f96220129fbb0453225cddeacdf00f6c to your computer and use it in GitHub Desktop.
Logger conifuration with StreamHandler and RotatingFileHandler
import logging
import os
import sys
from logging import Formatter
from logging import LogRecord
from logging import StreamHandler
from logging.handlers import RotatingFileHandler
class ColorFormatter(logging.Formatter):
grey = "\x1b[38;20m"
blue = "\x1b[38;5;39m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
colors = {
logging.DEBUG: grey,
logging.INFO: blue,
logging.WARNING: yellow,
logging.ERROR: red,
logging.CRITICAL: bold_red,
}
def format(self, record: LogRecord):
color = self.colors.get(record.levelno, self.grey)
message = super().format(record)
return color + message + self.reset
# intialize logger
root = logging.getLogger("chat")
root.setLevel(logging.DEBUG)
# formatter
fmt = "%(asctime)s - %(levelname)s - %(message)s"
datefmt = "%m/%d/%Y %I:%M:%S %p"
formatter = Formatter(fmt, datefmt)
color_formatter = ColorFormatter(fmt, datefmt)
# stream handler
stream_handler = StreamHandler(sys.stdout)
stream_handler.setFormatter(color_formatter)
stream_handler.setLevel(logging.INFO)
root.addHandler(stream_handler)
# file handler
file_path = os.path.join("logs", f"{root.name}.log")
dirname = os.path.dirname(file_path)
if dirname:
os.makedirs(dirname, exist_ok=True)
file_handler = RotatingFileHandler(
file_path, maxBytes=1_048_576, backupCount=100
) # 100 x 1 MB
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
root.addHandler(file_handler)
# ---------------------------------------------------------------------------
# Utility functions at module level.
# Basically delegate everything to the root logger.
# # ---------------------------------------------------------------------------
def critical(msg: str):
root.critical(msg)
def error(msg: str):
root.error(msg)
def exception(msg: str):
root.exception(msg)
def warning(msg: str):
root.warning(msg)
def info(msg: str):
root.info(msg)
def debug(msg: str):
root.debug(msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment