OpenTelemetry SQLite3 Instrumentation

0.62b0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to set up the OpenTelemetry SDK with a console exporter and then enable SQLite3 instrumentation. It's crucial to call `SQLite3Instrumentor().instrument()` before any `sqlite3.connect()` calls or module interactions to ensure all operations are traced. The example performs basic table creation, data insertion, and selection.

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")

view raw JSON →