Debian Codegraph @

docs/examples/plugins/prometheus/using_prometheus_exporter_with_extra_configs.py

raw
1 from typing import Any, Dict
2
3 from litestar import Litestar, Request
4 from litestar.plugins.prometheus import PrometheusConfig, PrometheusController
5
6
7 # We can modify the path of our custom handler and override the metrics format by subclassing the PrometheusController.
8 class CustomPrometheusController(PrometheusController):
9 path = "/custom-path"
10 openmetrics_format = True
11
12
13 # Let's assume this as our extra custom labels which we want our metrics to have.
14 # The values can be either a string or a callable that returns a string.
15 def custom_label_callable(request: Request[Any, Any, Any]) -> str:
16 return "v2.0"
17
18
19 extra_labels = {
20 "version_no": custom_label_callable,
21 "location": "earth",
22 }
23
24 # Customizing the buckets for the histogram.
25 buckets = [0.1, 0.2, 0.3, 0.4, 0.5]
26
27
28 # Adding exemplars to the metrics.
29 # Note that this supported only in openmetrics format.
30 def custom_exemplar(request: Request[Any, Any, Any]) -> Dict[str, str]:
31 return {"trace_id": "1234"}
32
33
34 # Creating the instance of PrometheusConfig with our own custom options.
35 # The given options are not necessary, you can use the default ones
36 # as well by just creating a raw instance PrometheusConfig()
37 prometheus_config = PrometheusConfig(
38 app_name="litestar-example",
39 prefix="litestar",
40 labels=extra_labels,
41 buckets=buckets, # pyright: ignore[reportArgumentType]
42 exemplars=custom_exemplar,
43 excluded_http_methods=["POST"],
44 )
45
46
47 # Creating the litestar app instance with our custom PrometheusConfig and PrometheusController.
48 app = Litestar(route_handlers=[CustomPrometheusController], middleware=[prometheus_config.middleware])