stephenhillier / starlette_exporter

Prometheus exporter for Starlette and FastAPI

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

status_code displays enum name in stats

jgould22 opened this issue · comments

When using code like the example below (with fastapi in this case)

from starlette_exporter import PrometheusMiddleware, handle_metrics
from http import HTTPStatus
from fastapi import FastAPI, HTTPException, Response
import uvicorn

app = FastAPI()
app.add_middleware(PrometheusMiddleware)
app.add_route("/metrics", handle_metrics)


@app.get("/")
async def root():
    return Response(status_code=HTTPStatus.OK)


@app.get("/200")
async def root():
    return {"I am returning 200"}


@app.get("/500")
async def root():
    raise HTTPException(status_code=500)
    return {"I am returning 200"}


@app.get("/500v2")
async def root():
    raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR)
    return {"I am returning 200"}


if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=5000, log_level="info")

The status code that is displayed in the metrics is the enum name, not the numeric code.

starlette_request_duration_seconds_bucket{app_name="starlette",le="10.0",method="GET",path="/",status_code="HTTPStatus.OK"} 2.0

Is this desired behaviour?

Perhaps it might be better to attempt to convert the status code to an int?

I think all we would have to do is maybe do a type check and convert to int right here
https://github.com/stephenhillier/starlette_exporter/blob/master/starlette_exporter/middleware.py#L174

Thanks for opening an issue! No, this was not intended. Unfortunately if anyone else is using HTTPStatus from the http library, they may have already set up their metrics to work with strings like HTTPStatus.OK so any changes could break things for them.

The only way I can think of to change this would be to add an option like always_use_int_status (naming suggestions welcome), and if that is set to true, always convert to int as you suggested. Any thoughts?

always_use_int_status seems entirely reasonable to me.

How about something like this jgould22@c7f9c47 ?

If you think that is acceptable I can get a pull request going.

No problem, I will put it in a pull request and you can get to it when you get to it.

Fixed in #49