Automated Action f44d1064ae Add request logging middleware to FastAPI application
Added RequestLoggingMiddleware that logs incoming HTTP requests with method, path, response status, and processing time using Python's built-in logging module.
2025-06-19 17:43:16 +00:00

38 lines
1.0 KiB
Python

import logging
import time
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("todo_app")
class RequestLoggingMiddleware(BaseHTTPMiddleware):
"""Middleware to log incoming HTTP requests"""
async def dispatch(self, request: Request, call_next):
# Log the incoming request
start_time = time.time()
logger.info(
f"Incoming request: {request.method} {request.url.path}"
)
# Process the request
response = await call_next(request)
# Calculate processing time
process_time = time.time() - start_time
# Log the response
logger.info(
f"Request completed: {request.method} {request.url.path} - "
f"Status: {response.status_code} - Time: {process_time:.4f}s"
)
return response