OpenTelemetry DBAPI Instrumentation

0.61b0 · active · verified Sun Mar 29

The `opentelemetry-instrumentation-dbapi` library provides OpenTelemetry tracing for Python applications interacting with databases via libraries that adhere to the Python Database API Specification v2.0 (PEP 249). It's part of the `opentelemetry-python-contrib` project, which typically follows a monthly release cadence. The current version, `0.61b0`, signifies that it is still in beta, and while functional, its API or behavior may be subject to change. This instrumentation offers core functionality for database tracing, and while users often prefer framework or ORM-specific instrumentations, it can be used directly when those are not available.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up the OpenTelemetry Python SDK with a `ConsoleSpanExporter` and then apply `opentelemetry-instrumentation-dbapi` to `mysql.connector`. It traces database operations, including connection, table creation, insertion, and selection, ensuring that these actions generate spans visible in the console. Environment variables are used for database credentials for a runnable example.

import os
import mysql.connector
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.dbapi import trace_integration

# Configure OpenTelemetry SDK
resource = {"service.name": os.environ.get('OTEL_SERVICE_NAME', 'dbapi-example')}
tracer_provider = TracerProvider.from_resource_attributes(resource)
tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(tracer_provider)

# Get a tracer
tracer = trace.get_tracer(__name__)

# Instrument the database connector (e.g., mysql.connector)
# Pass the module, the name of its connect method, and the database system identifier
trace_integration(mysql.connector, "connect", "mysql")

try:
    # Establish a connection using the instrumented module
    connection = mysql.connector.connect(
        host=os.environ.get('MYSQL_HOST', 'localhost'),
        user=os.environ.get('MYSQL_USER', 'root'),
        password=os.environ.get('MYSQL_PASSWORD', 'password'),
        database=os.environ.get('MYSQL_DATABASE', 'testdb')
    )

    with tracer.start_as_current_span("db-operations"):
        cursor = connection.cursor()
        cursor.execute("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))")
        cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
        connection.commit()
        cursor.execute("SELECT * FROM users")
        result = cursor.fetchall()
        print(f"Fetched result: {result}")
        cursor.close()

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    if 'connection' in locals() and connection.is_connected():
        connection.close()
    print("Application finished.")

view raw JSON →