OpenTelemetry SQLite3 Instrumentation
This library provides automatic instrumentation for the Python `sqlite3` module, enabling distributed tracing for database operations within applications. It's part of the `opentelemetry-python-contrib` repository, which follows a frequent release cadence, often aligning with core OpenTelemetry Python releases, with the current version being 0.62b0.
Warnings
- gotcha The package version (e.g., `0.62b0`) includes a 'b', indicating it's a beta release. While generally stable, minor API changes might occur in future beta versions before a stable `1.0.0` release.
- gotcha Instrumentation must be enabled *before* establishing any `sqlite3` connections or interacting with the `sqlite3` module. Connections made prior to `SQLite3Instrumentor().instrument()` will not be traced.
- gotcha Traces will not be exported or visible without a configured OpenTelemetry `TracerProvider`, `SpanProcessor`, and `SpanExporter`. The instrumentation only generates spans; the SDK is responsible for their processing and export.
- gotcha To ensure tracing support for database operations, cursor objects must be explicitly initialized. Direct usage of `connection.execute()` without an explicit cursor might not be fully traced in some scenarios.
Install
-
pip install opentelemetry-instrumentation-sqlite3
Imports
- SQLite3Instrumentor
from opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentor
Quickstart
import sqlite3
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.sqlite3 import SQLite3Instrumentor
# 1. Configure OpenTelemetry SDK
resource = Resource.create({"service.name": "sqlite3-example"})
provider = TracerProvider(resource=resource)
exporter = ConsoleSpanExporter()
processor = SimpleSpanProcessor(exporter)
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
# 2. Instrument SQLite3 BEFORE making any connections
SQLite3Instrumentor().instrument()
# 3. Perform SQLite3 operations
print("\nPerforming SQLite3 operations...")
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
cursor.execute("INSERT INTO users (name) VALUES ('Bob')")
conn.commit()
cursor.execute("SELECT * FROM users")
for row in cursor.fetchall():
print(f" Fetched: {row}")
cursor.close()
conn.close()
print("SQLite3 operations complete. Check console for traces.\n")