This release adds a `labels` argument to PrometheusMiddleware that accepts a dict of labels/values that will be added to all metrics.
Each label's value can be either a static value or, optionally, a callback function that takes the Request instance as its argument and returns a string.
Example:
python
app.add_middleware(
PrometheusMiddleware,
labels={
"service": "api",
"env": os.getenv("ENV"),
"my_header": lambda r: r.headers.get("X-My-Header")
}
)
Reminder: always evaluate the cardinality of sets of labels before using them, and do not use user-supplied values (e.g. untrusted headers) or unconstrained values to populate labels. See this for more information: https://grafana.com/blog/2022/02/15/what-are-cardinality-spikes-and-why-do-they-matter/
Thank you to intelroman for helping contribute to this feature.