{"library":"opentelemetry-instrumentation-sqlalchemy","code":"import os\nfrom opentelemetry import trace\nfrom opentelemetry.sdk.resources import Resource\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor\nfrom opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor\nfrom sqlalchemy import create_engine, text\n\n# Configure OpenTelemetry Tracer Provider\nresource = Resource.create({\"service.name\": os.environ.get(\"OTEL_SERVICE_NAME\", \"sqlalchemy-app\")})\ntracer_provider = TracerProvider(resource=resource)\ntracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))\ntrace.set_tracer_provider(tracer_provider)\n\n# Instrument SQLAlchemy\n# For global instrumentation of all engines, call without 'engine' argument:\n# SQLAlchemyInstrumentor().instrument()\n\n# For specific engine instrumentation:\nengine = create_engine(\"sqlite:///:memory:\")\nSQLAlchemyInstrumentor().instrument(engine=engine)\n\n# Use SQLAlchemy\nwith engine.connect() as connection:\n    connection.execute(text(\"CREATE TABLE users (id INTEGER, name TEXT)\"))\n    connection.execute(text(\"INSERT INTO users (id, name) VALUES (1, 'Alice')\"))\n    connection.execute(text(\"INSERT INTO users (id, name) VALUES (2, 'Bob')\"))\n    connection.commit()\n\n    result = connection.execute(text(\"SELECT * FROM users WHERE id = 1\"))\n    for row in result:\n        print(f\"User: {row.name}\")\n\nSQLAlchemyInstrumentor().uninstrument()\nprint(\"SQLAlchemy instrumentation demonstration complete.\")","lang":"python","description":"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.","tag":null,"tag_description":null,"last_tested":"2026-04-24","results":[{"runtime":"python:3.10-alpine","exit_code":1},{"runtime":"python:3.10-slim","exit_code":1},{"runtime":"python:3.11-alpine","exit_code":1},{"runtime":"python:3.11-slim","exit_code":1},{"runtime":"python:3.12-alpine","exit_code":1},{"runtime":"python:3.12-slim","exit_code":1},{"runtime":"python:3.13-alpine","exit_code":1},{"runtime":"python:3.13-slim","exit_code":1},{"runtime":"python:3.9-alpine","exit_code":1},{"runtime":"python:3.9-slim","exit_code":1}]}