OpenTelemetry SQLAlchemy Instrumentation

0.61b0 · active · verified Mon Apr 06

This library provides OpenTelemetry instrumentation for the SQLAlchemy Python library, allowing automatic tracing of database queries. It captures SQL statements, execution time, and connection information, providing insights into database operations within your application's distributed traces. Part of the `opentelemetry-python-contrib` project, it is currently in beta with frequent releases, often on a monthly cadence, aligning with the broader OpenTelemetry Python project.

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up OpenTelemetry tracing and instrument a SQLAlchemy engine. It uses an in-memory SQLite database for simplicity. The `SQLAlchemyInstrumentor().instrument(engine=engine)` call enables tracing for the specified engine. You can also call `SQLAlchemyInstrumentor().instrument()` without an `engine` argument to instrument all future SQLAlchemy engines created after that call. Traces are exported to the console.

import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from sqlalchemy import create_engine, text

# Configure OpenTelemetry Tracer Provider
resource = Resource.create({"service.name": os.environ.get("OTEL_SERVICE_NAME", "sqlalchemy-app")})
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(tracer_provider)

# Instrument SQLAlchemy
# For global instrumentation of all engines, call without 'engine' argument:
# SQLAlchemyInstrumentor().instrument()

# For specific engine instrumentation:
engine = create_engine("sqlite:///:memory:")
SQLAlchemyInstrumentor().instrument(engine=engine)

# Use SQLAlchemy
with engine.connect() as connection:
    connection.execute(text("CREATE TABLE users (id INTEGER, name TEXT)"))
    connection.execute(text("INSERT INTO users (id, name) VALUES (1, 'Alice')"))
    connection.execute(text("INSERT INTO users (id, name) VALUES (2, 'Bob')"))
    connection.commit()

    result = connection.execute(text("SELECT * FROM users WHERE id = 1"))
    for row in result:
        print(f"User: {row.name}")

SQLAlchemyInstrumentor().uninstrument()
print("SQLAlchemy instrumentation demonstration complete.")

view raw JSON →