Skip to content

Commit 617c516

Browse files
authored
feat(tracing): Add aiohttp request object to sampling context (#888)
1 parent ba1e550 commit 617c516

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

sentry_sdk/integrations/aiohttp.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,9 @@ async def sentry_app_handle(self, request, *args, **kwargs):
106106
# URL resolver did not find a route or died trying.
107107
name="generic AIOHTTP request",
108108
)
109-
110-
with hub.start_transaction(transaction):
109+
with hub.start_transaction(
110+
transaction, custom_sampling_context={"aiohttp_request": request}
111+
):
111112
try:
112113
response = await old_handle(self, request)
113114
except HTTPException as e:

tests/integrations/aiohttp/test_aiohttp.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,15 @@
55
import pytest
66
from aiohttp import web
77
from aiohttp.client import ServerDisconnectedError
8+
from aiohttp.web_request import Request
89

910
from sentry_sdk.integrations.aiohttp import AioHttpIntegration
1011

12+
try:
13+
from unittest import mock # python 3.3 and above
14+
except ImportError:
15+
import mock # python < 3.3
16+
1117

1218
async def test_basic(sentry_init, aiohttp_client, loop, capture_events):
1319
sentry_init(integrations=[AioHttpIntegration()])
@@ -223,3 +229,35 @@ async def hello(request):
223229

224230
assert event["type"] == "transaction"
225231
assert event["transaction"] == expected_transaction
232+
233+
234+
async def test_traces_sampler_gets_request_object_in_sampling_context(
235+
sentry_init,
236+
aiohttp_client,
237+
DictionaryContaining, # noqa:N803
238+
ObjectDescribedBy, # noqa:N803
239+
):
240+
traces_sampler = mock.Mock()
241+
sentry_init(
242+
integrations=[AioHttpIntegration()],
243+
traces_sampler=traces_sampler,
244+
)
245+
246+
async def kangaroo_handler(request):
247+
return web.Response(text="dogs are great")
248+
249+
app = web.Application()
250+
app.router.add_get("/tricks/kangaroo", kangaroo_handler)
251+
252+
client = await aiohttp_client(app)
253+
await client.get("/tricks/kangaroo")
254+
255+
traces_sampler.assert_any_call(
256+
DictionaryContaining(
257+
{
258+
"aiohttp_request": ObjectDescribedBy(
259+
type=Request, attrs={"method": "GET", "path": "/tricks/kangaroo"}
260+
)
261+
}
262+
)
263+
)

0 commit comments

Comments
 (0)