Skip to content

Commit

Permalink
send http.route attribute in flask metric
Browse files Browse the repository at this point in the history
  • Loading branch information
GonzaloGuasch committed May 7, 2024
1 parent 0a231e5 commit fa8cb3a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ def response_hook(span: Span, status: str, response_headers: List):
_ENVIRON_ACTIVATION_KEY = "opentelemetry-flask.activation_key"
_ENVIRON_REQCTX_REF_KEY = "opentelemetry-flask.reqctx_ref_key"
_ENVIRON_TOKEN = "opentelemetry-flask.token"
_ENVIRON_REQUEST_ROUTE_KEY = "request-route_key"

_excluded_urls_from_env = get_excluded_urls("FLASK")

Expand Down Expand Up @@ -344,6 +345,9 @@ def _start_response(status, response_headers, *args, **kwargs):
excluded_urls is None
or not excluded_urls.url_disabled(flask.request.url)
):
if flask.request.url_rule:
wrapped_app_environ[_ENVIRON_REQUEST_ROUTE_KEY] = str(flask.request.url_rule)

span = flask.request.environ.get(_ENVIRON_SPAN_KEY)

propagator = get_global_response_propagator()
Expand Down Expand Up @@ -386,13 +390,21 @@ def _start_response(status, response_headers, *args, **kwargs):
duration_attrs_old = otel_wsgi._parse_duration_attrs(
attributes, _HTTPStabilityMode.DEFAULT
)

if wrapped_app_environ.get(_ENVIRON_REQUEST_ROUTE_KEY, None):
duration_attrs_old[SpanAttributes.HTTP_ROUTE] = wrapped_app_environ.get(_ENVIRON_REQUEST_ROUTE_KEY)

duration_histogram_old.record(
max(round(duration_s * 1000), 0), duration_attrs_old
)
if duration_histogram_new:
duration_attrs_new = otel_wsgi._parse_duration_attrs(
attributes, _HTTPStabilityMode.HTTP
)

if wrapped_app_environ.get(_ENVIRON_REQUEST_ROUTE_KEY, None):
duration_attrs_new[SpanAttributes.HTTP_ROUTE] = wrapped_app_environ.get(_ENVIRON_REQUEST_ROUTE_KEY)

duration_histogram_new.record(
max(duration_s, 0), duration_attrs_new
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,7 @@ def test_exclude_lists_from_explicit(self):
self.assertEqual(len(span_list), 1)

def test_flask_metrics(self):
_server_duration_attrs_old.append("http.route")
start = default_timer()
self.client.get("/hello/123")
self.client.get("/hello/321")
Expand Down Expand Up @@ -570,6 +571,7 @@ def test_basic_metric_success(self):
self.client.get("/hello/756")
expected_duration_attributes = {
"http.method": "GET",
"http.route": "/hello/<int:helloid>",
"http.host": "localhost",
"http.scheme": "http",
"http.flavor": "1.1",
Expand Down Expand Up @@ -597,6 +599,7 @@ def test_basic_metric_success_new_semconv(self):
expected_duration_attributes = {
"http.request.method": "GET",
"url.scheme": "http",
"http.route": "/hello/<int:helloid>",
"network.protocol.version": "1.1",
"http.response.status_code": 200,
}
Expand Down

0 comments on commit fa8cb3a

Please sign in to comment.