import json import logging from logging.handlers import TimedRotatingFileHandler from typing import Any class JSONFormatter(logging.Formatter): def format(self, record): trace_id = record.msg.get("id") if trace_id: record.msg.pop("id") # Convert the log record to a dictionary log_dict = { "timestamp": record.created, "level": record.levelname, "message": json.dumps(record.msg, default=str), "traceback": None, "x-trace-id": trace_id, } # If the log record has an exception, capture the traceback information if record.exc_info: tb = self.formatException(record.exc_info) log_dict["traceback"] = tb # Return the log record as a JSON string return json.dumps(log_dict) def log_handler(log_file): handler = TimedRotatingFileHandler( filename=log_file, interval=1, when="D", ) handler.setFormatter(JSONFormatter()) return handler