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.
This commit is contained in:
Automated Action 2025-06-19 17:43:16 +00:00
parent 73197fb26f
commit f44d1064ae
3 changed files with 47 additions and 0 deletions

View File

38
app/middleware/logging.py Normal file
View File

@ -0,0 +1,38 @@
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

View File

@ -1,5 +1,7 @@
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from app.middleware.logging import RequestLoggingMiddleware
from app.api.router import api_router
app = FastAPI( app = FastAPI(
title="Todo App API", title="Todo App API",
@ -8,6 +10,9 @@ app = FastAPI(
openapi_url="/openapi.json" openapi_url="/openapi.json"
) )
# Add request logging middleware
app.add_middleware(RequestLoggingMiddleware)
# Configure CORS to allow all origins # Configure CORS to allow all origins
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
@ -36,6 +41,10 @@ async def health_check():
return {"status": "healthy", "message": "Todo App API is running"} return {"status": "healthy", "message": "Todo App API is running"}
# Include API router
app.include_router(api_router, prefix="/api/v1")
if __name__ == "__main__": if __name__ == "__main__":
import uvicorn import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) uvicorn.run(app, host="0.0.0.0", port=8000)