Skip to content

Commit

Permalink
wrap sqlalchemy.engine.create.create_engine
Browse files Browse the repository at this point in the history
sqlalchemy.engine_from_config directly calls create_engine imported from that path; if we don't
wrap that copy of the `create_engine` call then engines created via engine_from_config are not
instrumented.
  • Loading branch information
moredip committed Aug 23, 2024
1 parent 1ad9d90 commit 9f40f5d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,13 @@ def _instrument(self, **kwargs):
tracer, connections_usage, enable_commenter, commenter_options
),
)
_w(
"sqlalchemy.engine.create",
"create_engine",
_wrap_create_engine(
tracer, connections_usage, enable_commenter, commenter_options
),
)
_w(
"sqlalchemy.engine.base",
"Engine.connect",
Expand Down Expand Up @@ -223,6 +230,7 @@ def _instrument(self, **kwargs):
def _uninstrument(self, **kwargs):
unwrap(sqlalchemy, "create_engine")
unwrap(sqlalchemy.engine, "create_engine")
unwrap(sqlalchemy.engine.create, "create_engine")
unwrap(Engine, "connect")
if parse_version(sqlalchemy.__version__).release >= (1, 4):
unwrap(sqlalchemy.ext.asyncio, "create_async_engine")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,17 @@ def test_create_engine_wrapper(self):
"opentelemetry.instrumentation.sqlalchemy",
)

def test_instrument_engine_from_config(self):
SQLAlchemyInstrumentor().instrument()
from sqlalchemy import engine_from_config # pylint: disable-all

engine = engine_from_config({"sqlalchemy.url": "sqlite:///:memory:"})
cnx = engine.connect()
cnx.execute("SELECT 1 + 1;").fetchall()
spans = self.memory_exporter.get_finished_spans()

self.assertEqual(len(spans), 2)

def test_create_engine_wrapper_enable_commenter(self):
logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO)
SQLAlchemyInstrumentor().instrument(
Expand Down

0 comments on commit 9f40f5d

Please sign in to comment.