8000 Fix asyncpg spans (#3639) · getsentry/sentry-python@ef7c39c · GitHub
[go: up one dir, main page]

Skip to content

Commit ef7c39c

Browse files
authored
Fix asyncpg spans (#3639)
- Change `span.set_data` to `span.set_attribute` - Change `start_transaction`s in the tests to `start_span`s - Stringify `db.params`, `db.paramstyle`, `db.cursor` - ❗ Change how adding query source works. Previously, we first let the DB span finish and then looked at its start and end timestamps to figure out if the query was slow enough to attach query data. With the switch to OTel, we can no longer put stuff on a finished span, meaning the slow query span still has to be alive when adding data to it. So instead of looking at the end timestamp of a finished span, we keep the span alive and instead look at current time at the point when the query is finished. This means the DB span will be longer than the actual query (since it now includes adding query data).
1 parent f9187be commit ef7c39c

File tree

3 files changed

+123
-82
lines changed

3 files changed

+123
-82
lines changed

sentry_sdk/integrations/asyncpg.py

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ def setup_once() -> None:
4040
asyncpg.Connection.execute = _wrap_execute(
4141
asyncpg.Connection.execute,
4242
)
43-
4443
asyncpg.Connection._execute = _wrap_connection_method(
4544
asyncpg.Connection._execute
4645
)
@@ -80,8 +79,8 @@ async def _inner(*args: Any, **kwargs: Any) -> T:
8079
) as span:
8180
res = await f(*args, **kwargs)
8281

83-
with capture_internal_exceptions():
84-
add_query_source(span)
82+
with capture_internal_exceptions():
83+
add_query_source(span)
8584

8685
return res
8786

@@ -148,7 +147,7 @@ def _inner(*args: Any, **kwargs: Any) -> T: # noqa: N807
148147
) as span:
149148
_set_db_data(span, args[0])
150149
res = f(*args, **kwargs)
151-
span.set_data("db.cursor", res)
150+
span.set_attribute("db.cursor", str(res))
152151
153152
return res
154153

@@ -168,21 +167,37 @@ async def _inner(*args: Any, **kwargs: Any) -> T:
168167
name="connect",
169168
origin=AsyncPGIntegration.origin,
170169
) as span:
171-
span.set_data(SPANDATA.DB_SYSTEM, "postgresql")
170+
span.set_attribute(SPANDATA.DB_SYSTEM, "postgresql")
172171
addr = kwargs.get("addr")
173172
if addr:
174173
try:
175-
span.set_data(SPANDATA.SERVER_ADDRESS, addr[0])
176-
span.set_data(SPANDATA.SERVER_PORT, addr[1])
174+
span.set_attribute(SPANDATA.SERVER_ADDRESS, addr[0])
175+
span.set_attribute(SPANDATA.SERVER_PORT, addr[1])
177176
except IndexError:
178177
pass
179-
span.set_data(SPANDATA.DB_NAME, database)
180-
span.set_data(SPANDATA.DB_USER, user)
178+
179+
span.set_attribute(SPANDATA.DB_NAME, database)
180+
span.set_attribute(SPANDATA.DB_USER, user)
181181

182182
with capture_internal_exceptions():
183+
data = {}
184+
for attr in (
185+
"db.cursor",
186+
"db.params",
187+
"db.paramstyle",
188+
SPANDATA.DB_NAME,
189+
SPANDATA.DB_SYSTEM,
190+
SPANDATA.DB_USER,
191+
SPANDATA.SERVER_ADDRESS,
192+
SPANDATA.SERVER_PORT,
193+
):
194+
if span.get_attribute(attr):
195+
data[attr] = span.get_attribute(attr)
196+
183197
sentry_sdk.add_breadcrumb(
184-
message="connect", category="query", data=span._data
198+
message="connect", category="query", data=data
185199
)
200+
186201
res = await f(*args, **kwargs)
187202

188203
return res
@@ -191,20 +206,20 @@ async def _inner(*args: Any, **kwargs: Any) -> T:
191206

192207

193208
def _set_db_data(span: Span, conn: Any) -> None:
194-
span.set_data(SPANDATA.DB_SYSTEM, "postgresql")
209+
span.set_attribute(SPANDATA.DB_SYSTEM, "postgresql")
195210

196211
addr = conn._addr
197212
if addr:
198213
try:
199-
span.set_data(SPANDATA.SERVER_ADDRESS, addr[0])
200-
span.set_data(SPANDATA.SERVER_PORT, addr[1])
214+
span.set_attribute(SPANDATA.SERVER_ADDRESS, addr[0])
215+
span.set_attribute(SPANDATA.SERVER_PORT, addr[1])
201216
except IndexError:
202217
pass
203218

204219
database = conn._params.database
205220
if database:
206-
span.set_data(SPANDATA.DB_NAME, database)
221+
span.set_attribute(SPANDATA.DB_NAME, database)
207222

208223
user = conn._params.user
209224
if user:
210-
span.set_data(SPANDATA.DB_USER, user)
225+
span.set_attribute(SPANDATA.DB_USER, user)

sentry_sdk/tracing_utils.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import re
55
import sys
66
from collections.abc import Mapping
7-
from datetime import timedelta
7+
from datetime import datetime, timedelta, timezone
88
from functools import wraps
99
from urllib.parse import quote, unquote
1010
import uuid
@@ -133,13 +133,13 @@ def record_sql_queries(
133133

134134
data = {}
135135
if params_list is not None:
136-
data["db.params"] = params_list
136+
data["db.params"] = str(params_list)
137137
if paramstyle is not None:
138-
data["db.paramstyle"] = paramstyle
138+
data["db.paramstyle"] = str(paramstyle)
139139
if executemany:
140140
data["db.executemany"] = True
141141
if record_cursor_repr and cursor is not None:
142-
data["db.cursor"] = cursor
142+
data["db.cursor"] = str(cursor)
143143

144144
with capture_internal_exceptions():
145145
sentry_sdk.add_breadcrumb(message=query, category="query", data=data)
@@ -209,14 +209,17 @@ def add_query_source(span):
209209
if not client.is_active():
210210
return
211211

212-
if span.timestamp is None or span.start_timestamp is None:
212+
if span.start_timestamp is None:
213213
return
214214

215215
should_add_query_source = client.options.get("enable_db_query_source", True)
216216
if not should_add_query_source:
217217
return
218218

219-
duration = span.timestamp - span.start_timestamp
219+
# We assume here that the query is just ending now. We can't use
220+
# the actual end timestamp of the span because in OTel the span
221+
# can't be finished in order to set any attributes on it.
222+
duration = datetime.now(tz=timezone.utc) - span.start_timestamp
220223
threshold = client.options.get("db_query_source_threshold_ms", 0)
221224
slow_query = duration / timedelta(milliseconds=1) > threshold
222225

0 commit comments

Comments
 (0)
0