Skip to content

Commit

Permalink
Trace request attributes before invoking middleware
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mmcfarland committed Oct 24, 2022
1 parent ca4346b commit 9613098
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions pccommon/pccommon/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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)
)
Expand All @@ -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)
Expand Down

0 comments on commit 9613098

Please sign in to comment.