1111from starlette .routing import Match
1212from starlette .status import HTTP_500_INTERNAL_SERVER_ERROR
1313
14- from asgi_monitor .metrics import get_latest_metrics
15- from asgi_monitor .metrics .container import MetricsContainer
16- from asgi_monitor .metrics .manager import MetricsManager
17-
1814if TYPE_CHECKING :
1915 from starlette .applications import Starlette
2016 from starlette .requests import Request
2117 from starlette .types import ASGIApp , Receive , Scope , Send
2218
19+ from asgi_monitor .metrics import get_latest_metrics
20+ from asgi_monitor .metrics .config import CommonMetricsConfig
21+ from asgi_monitor .metrics .container import MetricsContainer
22+ from asgi_monitor .metrics .manager import MetricsManager
2323from asgi_monitor .tracing .config import CommonTracingConfig
2424from asgi_monitor .tracing .middleware import build_open_telemetry_middleware
2525
2626__all__ = (
2727 "TracingConfig" ,
2828 "TracingMiddleware" ,
29- "MetricsMiddleware" ,
3029 "setup_tracing" ,
30+ "MetricsConfig" ,
31+ "MetricsMiddleware" ,
3132 "setup_metrics" ,
3233)
3334
@@ -69,13 +70,15 @@ def _get_path(request: Request) -> tuple[str, bool]:
6970
7071@dataclass
7172class TracingConfig (CommonTracingConfig ):
72- """Configuration class for the OpenTelemetry middleware.
73+ """
74+ Configuration class for the OpenTelemetry middleware.
7375 Consult the OpenTelemetry ASGI documentation for more info about the configuration options.
7476 https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/asgi/asgi.html
7577 """
7678
7779 exclude_urls_env_key : str = "STARLETTE"
78- """Key to use when checking whether a list of excluded urls is passed via ENV.
80+ """
81+ Key to use when checking whether a list of excluded urls is passed via ENV.
7982 OpenTelemetry supports excluding urls by passing an env in the format '{exclude_urls_env_key}_EXCLUDED_URLS'.
8083 """
8184
@@ -86,6 +89,14 @@ class TracingConfig(CommonTracingConfig):
8689 """
8790
8891
92+ @dataclass
93+ class MetricsConfig (CommonMetricsConfig ):
94+ """Configuration class for the Metrics middleware."""
95+
96+ metrics_prefix : str = "starlette"
97+ """The prefix to use for the metrics."""
98+
99+
89100class TracingMiddleware :
90101 def __init__ (self , app : ASGIApp , config : TracingConfig ) -> None :
91102 self .app = app
@@ -108,12 +119,11 @@ def __init__(
108119 self ,
109120 app : ASGIApp ,
110121 app_name : str ,
111- metrics_prefix : str ,
122+ container : MetricsContainer ,
112123 * ,
113124 include_trace_exemplar : bool ,
114125 ) -> None :
115126 super ().__init__ (app )
116- container = MetricsContainer (prefix = metrics_prefix )
117127 self .metrics = MetricsManager (app_name = app_name , container = container )
118128 self .include_exemplar = include_trace_exemplar
119129 self .metrics .add_app_info ()
@@ -166,7 +176,8 @@ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -
166176
167177
168178async def get_metrics (request : Request ) -> Response :
169- response = get_latest_metrics (openmetrics_format = False )
179+ registry = request .app .state .metrics_registry
180+ response = get_latest_metrics (registry , openmetrics_format = False )
170181 return Response (
171182 content = response .payload ,
172183 status_code = response .status_code ,
@@ -187,34 +198,24 @@ def setup_tracing(app: Starlette, config: TracingConfig) -> None:
187198 app .add_middleware (TracingMiddleware , config = config )
188199
189200
190- def setup_metrics (
191- app : Starlette ,
192- app_name : str ,
193- metrics_prefix : str = "starlette" ,
194- * ,
195- include_trace_exemplar : bool ,
196- include_metrics_endpoint : bool ,
197- ) -> None :
201+ def setup_metrics (app : Starlette , config : MetricsConfig ) -> None :
198202 """
199203 Set up metrics for a Starlette application.
200204 This function adds a MetricsMiddleware to the Starlette application with the specified parameters.
201- If include_metrics_endpoint is True, it also adds a route for "/metrics" that returns Prometheus default metrics.
202205
203206 :param Starlette app: The Starlette application instance.
204- :param str app_name: The name of the Starlette application.
205- :param str metrics_prefix: The prefix to use for the metrics (default is "starlette").
206- :param bool include_trace_exemplar: Whether to include trace exemplars in the metrics.
207- :param bool include_metrics_endpoint: Whether to include a /metrics endpoint.
207+ :param MetricsConfig config: Configuration for the metrics.
208208 :returns: None
209209 """
210210
211+ app .state .metrics_registry = config .registry
211212 app .add_middleware (
212213 MetricsMiddleware ,
213- app_name = app_name ,
214- metrics_prefix = metrics_prefix ,
215- include_trace_exemplar = include_trace_exemplar ,
214+ app_name = config . app_name ,
215+ container = MetricsContainer ( config . metrics_prefix , config . registry ) ,
216+ include_trace_exemplar = config . include_trace_exemplar ,
216217 )
217- if include_metrics_endpoint :
218+ if config . include_metrics_endpoint :
218219 app .add_route (
219220 path = "/metrics" ,
220221 route = get_metrics ,
0 commit comments