From 9613098c8ba2b756cbbb543f0be930205f183e3e Mon Sep 17 00:00:00 2001 From: Matt McFarland Date: Mon, 24 Oct 2022 10:32:38 -0400 Subject: [PATCH] Trace request attributes before invoking middleware If an exception is raised in subsequent middlewares, added trace attributes will still be logged to Azure. This allows us to find requests that fail in the logs. --- pccommon/pccommon/tracing.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/pccommon/pccommon/tracing.py b/pccommon/pccommon/tracing.py index 948f1415..80aabc1e 100644 --- a/pccommon/pccommon/tracing.py +++ b/pccommon/pccommon/tracing.py @@ -62,8 +62,7 @@ async def trace_request( # are slow. request.state.parent_span = span - response = await call_next(request) - + # Add request dimensions to the trace prior to calling the next middleware tracer.add_attribute_to_current_span( attribute_key="ref_id", attribute_value=request.headers.get(X_AZURE_REF), @@ -76,9 +75,6 @@ async def trace_request( attribute_key="request_ip", attribute_value=get_request_ip(request), ) - tracer.add_attribute_to_current_span( - attribute_key=HTTP_STATUS_CODE, attribute_value=response.status_code - ) tracer.add_attribute_to_current_span( attribute_key=HTTP_METHOD, attribute_value=str(request.method) ) @@ -103,6 +99,13 @@ async def trace_request( attribute_key="item", attribute_value=item_id ) + # Call next middleware + response = await call_next(request) + + # Include response dimensions in the trace + tracer.add_attribute_to_current_span( + attribute_key=HTTP_STATUS_CODE, attribute_value=response.status_code + ) return response else: return await call_next(request)