Added Prometheus metric endpoint on port 9000
This commit is contained in:
parent
799ecdda67
commit
7fb139b362
@ -9,6 +9,7 @@ fastapi==0.118.0
|
||||
h11==0.16.0
|
||||
idna==3.10
|
||||
mysql-connector-python==9.4.0
|
||||
prometheus_client==0.23.1
|
||||
pycparser==2.23
|
||||
pydantic==2.12.0
|
||||
pydantic_core==2.41.1
|
||||
|
||||
24
src/main.py
24
src/main.py
@ -13,7 +13,8 @@ from hashlib import sha256
|
||||
import uvicorn
|
||||
from uvicorn_logging_config import LOGGING_CONFIG
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from metrics_server import REQUEST_COUNTER
|
||||
import asyncio
|
||||
|
||||
|
||||
logger = setup_logger(__name__)
|
||||
@ -52,6 +53,11 @@ api = FastAPI(
|
||||
lifespan=lifespan
|
||||
)
|
||||
|
||||
@api.middleware("http")
|
||||
async def prometheus_middleware(request, call_next):
|
||||
response = await call_next(request)
|
||||
REQUEST_COUNTER.labels(request.method, request.url.path, response.status_code).inc()
|
||||
return response
|
||||
|
||||
def verify_api_key_dependency(db=Depends(get_db), api_key: str = Depends(api_key_header)) -> int:
|
||||
cursor = db.cursor()
|
||||
@ -152,12 +158,14 @@ def unregister_token(
|
||||
logger.info(f"Success: Unregistering token for user_id={user_id}, platform={request_data.platform}")
|
||||
return {"status":"unregistered"}
|
||||
|
||||
async def start_servers():
|
||||
config_main = uvicorn.Config("main:api", host="0.0.0.0", port=8100, log_config=LOGGING_CONFIG, log_level="info")
|
||||
config_metrics = uvicorn.Config("metrics_server:metrics_api", host="0.0.0.0", port=9000, log_level="info")
|
||||
|
||||
server_main = uvicorn.Server(config_main)
|
||||
server_metrics = uvicorn.Server(config_metrics)
|
||||
|
||||
await asyncio.gather(server_main.serve(), server_metrics.serve())
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(
|
||||
"main:api",
|
||||
host="0.0.0.0",
|
||||
port=8100,
|
||||
log_config=LOGGING_CONFIG,
|
||||
log_level="info"
|
||||
)
|
||||
asyncio.run(start_servers())
|
||||
|
||||
10
src/metrics_server.py
Normal file
10
src/metrics_server.py
Normal file
@ -0,0 +1,10 @@
|
||||
from fastapi import FastAPI, Response
|
||||
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST, Counter
|
||||
|
||||
metrics_api = FastAPI(title="Metrics Server", description="Prometheus metrics endpoint")
|
||||
|
||||
REQUEST_COUNTER = Counter("http_requests_total", "Total HTTP Requests", ["method", "endpoint", "status"])
|
||||
|
||||
@metrics_api.get("/metrics")
|
||||
async def metrics():
|
||||
return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)
|
||||
Loading…
x
Reference in New Issue
Block a user