Skip to content

Commit

Permalink
forgot to add the files
Browse files Browse the repository at this point in the history
  • Loading branch information
extreme4all committed Nov 29, 2024
1 parent a8a5681 commit b3e5daf
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 0 deletions.
Empty file added src/core/fastapi/__init__.py
Empty file.
4 changes: 4 additions & 0 deletions src/core/fastapi/middleware/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from .logging import LoggingMiddleware
from .metrics import PrometheusMiddleware

__all__ = ["LoggingMiddleware", "PrometheusMiddleware"]
28 changes: 28 additions & 0 deletions src/core/fastapi/middleware/logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import logging
import time

from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware

logger = logging.getLogger(__name__)


class LoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
start_time = time.perf_counter()
response = await call_next(request)
process_time = time.perf_counter() - start_time

query_params_list = [
(key, value if key != "token" else "***")
for key, value in request.query_params.items()
]

logger.info(
{
"url": request.url.path,
"params": query_params_list,
"process_time": f"{process_time:.4f}",
}
)
return response
38 changes: 38 additions & 0 deletions src/core/fastapi/middleware/metrics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from prometheus_client.metrics import Counter, Histogram

import time
from starlette.middleware.base import BaseHTTPMiddleware
from fastapi import Request

# Define Prometheus metrics
REQUEST_COUNT = Counter(
"request_count", "Total number of requests", ["method", "endpoint", "http_status"]
)
REQUEST_LATENCY = Histogram(
"request_latency_seconds", "Latency of requests in seconds", ["method", "endpoint"]
)


# Middleware for Prometheus metrics logging
class PrometheusMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
REQUEST_COUNT.labels(
method=request.method,
endpoint=request.url.path
).inc()

# Start timer for request latency
start_time = time.perf_counter()

# Process request
response = await call_next(request)

# Calculate request latency
latency = time.perf_counter() - start_time

REQUEST_LATENCY.labels(
method=request.method,
endpoint=request.url.path,
).observe(latency)

return response

0 comments on commit b3e5daf

Please sign in to comment.