open-telemetry / opentelemetry-python-contrib

OpenTelemetry instrumentation for Python modules
https://opentelemetry.io
Apache License 2.0
704 stars 589 forks source link

Document how to instrument SQLAlchemy manually for PostgreSQL #1648

Open AkselAllas opened 1 year ago

AkselAllas commented 1 year ago

How can I instrument PostgreSQL SQLAlchemy manually? I got it working using autoinstrumentation, but not using manual instrumentation. (Which I need since some GCP trace propagation doesn't work otherwise)

I tried these (but doesn't work, only connect span is created):

from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
SQLAlchemyInstrumentor().instrument()
dbapi.trace_integration(engine, "connect", "PostgreSQL")
AkselAllas commented 1 year ago

🤦 The following works: (Thanks person, who commented and uncommented!)

SQLAlchemyInstrumentor().instrument(engine=self.engine)
vanchaxy commented 11 months ago

If you encounter this issue while using AsyncEngine, please be aware that you need to use SQLAlchemyInstrumentor().instrument(engine=engine.sync_engine) for instrumentation. This is because AsyncEngine does not support event listeners.

nioncode commented 1 week ago

We are facing the same issue. If we just setup the instrumentation via SQLAlchemyInstrumentor().instrument() and leave out the engine, we only see connect calls in the spans. If we add the engine via SQLAlchemyInstrumentor().instrument(engine=db.engine), then the sql statements itself show up.

Is this expected behavior? The documentation does not describe when you need to pass the engine, so we assumed the basic setup just instruments everything (since it instruments create_engine we assumed it would also instrument all the created engines). Is this not the case?