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:
parent
73197fb26f
commit
f44d1064ae
0
app/middleware/__init__.py
Normal file
0
app/middleware/__init__.py
Normal file
38
app/middleware/logging.py
Normal file
38
app/middleware/logging.py
Normal 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
|
9
main.py
9
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)
|
Loading…
x
Reference in New Issue
Block a user