Skip to content

Commit 44454ef

Browse files
author
Oliver Paraskos
committed
Populate db.statement when Composable passed to cursor.execute
1 parent 52ff7bd commit 44454ef

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

instrumentation/opentelemetry-instrumentation-aiopg/src/opentelemetry/instrumentation/aiopg/aiopg_integration.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from collections.abc import Coroutine
44

55
import wrapt
6+
from psycopg2.sql import Composable # pylint: disable=no-name-in-module
67

78
from opentelemetry.instrumentation.dbapi import (
89
CursorTracer,
@@ -121,6 +122,18 @@ async def traced_execution(
121122
self._populate_span(span, cursor, *args)
122123
return await query_method(*args, **kwargs)
123124

125+
def get_operation_name(self, cursor, args):
126+
if len(args) and isinstance(args[0], Composable):
127+
return args[0].as_string(cursor)
128+
129+
return super().get_operation_name(cursor, args)
130+
131+
def get_statement(self, cursor, args):
132+
if len(args) and isinstance(args[0], Composable):
133+
return args[0].as_string(cursor)
134+
135+
return super().get_statement(cursor, args)
136+
124137

125138
def get_traced_cursor_proxy(cursor, db_api_integration, *args, **kwargs):
126139
_traced_cursor = AsyncCursorTracer(db_api_integration)

instrumentation/opentelemetry-instrumentation-aiopg/tests/test_aiopg_integration.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,24 @@ def test_uninstrument_connection(self):
495495
connection4 = wrappers.uninstrument_connection(connection)
496496
self.assertIs(connection4, connection)
497497

498+
def test_composable(self):
499+
from psycopg2 import sql
500+
501+
db_integration = AiopgIntegration(self.tracer, "testcomponent")
502+
mock_connection = async_call(
503+
db_integration.wrapped_connection(mock_connect, {}, {})
504+
)
505+
cursor = async_call(mock_connection.cursor())
506+
async_call(cursor.execute(sql.SQL("SELECT * FROM my_table")))
507+
spans_list = self.memory_exporter.get_finished_spans()
508+
509+
self.assertEqual(len(spans_list), 1)
510+
span = spans_list[0]
511+
self.assertEqual(
512+
span.attributes[SpanAttributes.DB_STATEMENT],
513+
"SELECT * FROM my_table",
514+
)
515+
498516

499517
# pylint: disable=unused-argument
500518
async def mock_connect(*args, **kwargs):

0 commit comments

Comments
 (0)