Skip to content

Commit

Permalink
CB-5 Add logging middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
izzat5233 committed Oct 21, 2024
1 parent d9e8721 commit b704779
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
3 changes: 3 additions & 0 deletions app/core/middlewares/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .logging_middleware import log_request_response_middleware

__all__ = ["log_request_response_middleware"]
16 changes: 16 additions & 0 deletions app/core/middlewares/logging_middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from fastapi import Request
from app.core.logger import logger
import time


async def log_request_response_middleware(request: Request, call_next):
start_time = time.time()
logger.info(f"Request: {request.method} {request.url}")

# Call the next handler
response = await call_next(request)

process_time = time.time() - start_time
logger.info(f"Response: {response.status_code} (Time: {process_time:.2f}s)")

return response
4 changes: 4 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from fastapi import FastAPI
from app.api.v1.routers.test_router import router as test_router
from app.core.middlewares import log_request_response_middleware

# Create the FastAPI application
app = FastAPI(
Expand All @@ -8,5 +9,8 @@
version="1.0.0"
)

# Register the middlewares
app.middleware("http")(log_request_response_middleware)

# Register the controllers
app.include_router(test_router, prefix="/v1", tags=["Test"])

0 comments on commit b704779

Please sign in to comment.