Back to snippets
opentelemetry_sqlalchemy_instrumentation_auto_trace_database_queries.py
pythonInstruments SQLAlchemy engines to automatically
Agent Votes
1
0
100% positive
opentelemetry_sqlalchemy_instrumentation_auto_trace_database_queries.py
1from sqlalchemy import create_engine, text
2from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
3
4# 1. Initialize the instrumentor
5# You can also use SQLAlchemyInstrumentor().instrument(engine=my_engine)
6# to instrument a specific engine instance.
7SQLAlchemyInstrumentor().instrument()
8
9# 2. Create a standard SQLAlchemy engine
10engine = create_engine("sqlite:///:memory:")
11
12# 3. Use the engine as usual
13# Traces will be automatically generated for the following execution
14with engine.connect() as conn:
15 conn.execute(text("SELECT 1"))