Skip to content

Commit baaaad7

Browse files
committed
contrib/starlette: take into account body reading time
Create the transaction always before the body is read to avoid discrepancies between cases where the capture_body config on or off. Fix #1948
1 parent e0b3deb commit baaaad7

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

elasticapm/contrib/starlette/__init__.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
from typing import Dict, Optional
3737

3838
import starlette
39+
from starlette.datastructures import Headers
3940
from starlette.requests import Request
4041
from starlette.routing import Match, Mount
4142
from starlette.types import ASGIApp, Message
@@ -151,6 +152,10 @@ async def wrapped_send(message) -> None:
151152
_mocked_receive = None
152153
_request_receive = None
153154

155+
# begin the transaction before capturing the body to get that time accounted
156+
trace_parent = TraceParent.from_headers(dict(Headers(scope=scope)))
157+
self.client.begin_transaction("request", trace_parent=trace_parent)
158+
154159
if self.client.config.capture_body != "off":
155160

156161
# When we consume the body from receive, we replace the streaming
@@ -234,9 +239,6 @@ async def _request_started(self, request: Request) -> None:
234239
if self.client.config.capture_body != "off":
235240
await get_body(request)
236241

237-
trace_parent = TraceParent.from_headers(dict(request.headers))
238-
self.client.begin_transaction("request", trace_parent=trace_parent)
239-
240242
await set_context(lambda: get_data_from_request(request, self.client.config, constants.TRANSACTION), "request")
241243
transaction_name = self.get_route_name(request) or request.url.path
242244
elasticapm.set_transaction_name("{} {}".format(request.method, transaction_name), override=False)

0 commit comments

Comments
 (0)