Skip to content
This repository was archived by the owner on Sep 13, 2023. It is now read-only.

serve fastapi: expose /metrics endpoint for Prometheus #591

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions mlem/contrib/fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from fastapi import FastAPI, UploadFile
from fastapi.datastructures import Default
from fastapi.responses import RedirectResponse
from prometheus_fastapi_instrumentator import Instrumentator
from pydantic import BaseModel, create_model, parse_obj_as
from pydantic.typing import get_args
from starlette.responses import JSONResponse, Response, StreamingResponse
Expand Down Expand Up @@ -58,6 +59,8 @@ class FastAPIServer(Server, LibRequirementsMixin):
"""Network interface to use"""
port: int = 8080
"""Port to use"""
metrics: bool = False
"""Generate /metrics endpoint to be scraped by Prometheus"""

@classmethod
def _create_handler_executor(
Expand Down Expand Up @@ -197,6 +200,12 @@ def app_init(self, interface: Interface):
response_class=response_class or Default(JSONResponse),
)

if self.metrics:

@app.on_event("startup")
async def startup():
Instrumentator().instrument(app).expose(app)

return app

def serve(self, interface: Interface):
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
"catboost": ["catboost"],
"xgboost": ["xgboost"],
"lightgbm": ["lightgbm"],
"fastapi": ["uvicorn", "fastapi"],
"fastapi": ["uvicorn", "fastapi", "prometheus-fastapi-instrumentator"],
"streamlit": ["uvicorn", "fastapi", "streamlit", "streamlit_pydantic"],
"sagemaker": ["docker", "boto3", "sagemaker"],
"torch": ["torch"],
Expand Down