From f44d1064ae3dc6e13e444257c0d90118dcd7a9a2 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Thu, 19 Jun 2025 17:43:16 +0000 Subject: [PATCH] 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. --- app/middleware/__init__.py | 0 app/middleware/logging.py | 38 ++++++++++++++++++++++++++++++++++++++ main.py | 9 +++++++++ 3 files changed, 47 insertions(+) create mode 100644 app/middleware/__init__.py create mode 100644 app/middleware/logging.py diff --git a/app/middleware/__init__.py b/app/middleware/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/middleware/logging.py b/app/middleware/logging.py new file mode 100644 index 0000000..28bb26a --- /dev/null +++ b/app/middleware/logging.py @@ -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 \ No newline at end of file diff --git a/main.py b/main.py index 7865ed0..c760c7c 100644 --- a/main.py +++ b/main.py @@ -1,5 +1,7 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware +from app.middleware.logging import RequestLoggingMiddleware +from app.api.router import api_router app = FastAPI( title="Todo App API", @@ -8,6 +10,9 @@ app = FastAPI( openapi_url="/openapi.json" ) +# Add request logging middleware +app.add_middleware(RequestLoggingMiddleware) + # Configure CORS to allow all origins app.add_middleware( CORSMiddleware, @@ -36,6 +41,10 @@ async def health_check(): return {"status": "healthy", "message": "Todo App API is running"} +# Include API router +app.include_router(api_router, prefix="/api/v1") + + if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file