Registry / observability / opentelemetry-instrumentation-dbapi

opentelemetry-instrumentation-dbapi

JSON →
library0.61b0pypypiunverified

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.

observabilitydatabase
pip install opentelemetry-instrumentation-dbapi opentelemetry-sdk mysql-connector-python
Install & Compatibility
Where this runs
tested against v0.63b1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.925 runs
installs and imports cleanly · install 0.0s · import 0.342s · 27.5MB
glibc
py 3.103.925 runs
installs and imports cleanly · install 3.3s · import 0.311s · 89MB
59MB installed
● package 59MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

trace_integration
from opentelemetry.instrumentation.dbapi import trace_integration
from opentelemetry.instrumentation.dbapi import DbApiInstrumentor
The DbApiInstrumentor class is not directly exposed or the primary way to enable instrumentation; 'trace_integration' and 'wrap_connect' are the public functions.

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.")
Debug
Known issues
breakingOpenTelemetry Python contrib packages, including `opentelemetry-instrumentation-dbapi`, are often in beta (indicated by `b0` suffix). This means API changes and breaking modifications can occur between minor versions without strict adherence to semantic versioning until a stable `1.0.0` release. Semantic conventions, which define attribute names and structures, also evolve and may require updates to instrumentation configurations. For example, the `db.statement` attribute's inclusion of sqlcomment became opt-in in previous versions.
fix
Regularly review the `opentelemetry-python-contrib` CHANGELOG for specific instrumentation packages and adapt your code to new APIs or semantic conventions. Pin major versions in `requirements.txt`.
affects: All beta versions (`<1.0.0`)
gotchaIncorrectly identifying the `connect` method name for your DBAPI driver is a common mistake. For instance, `pyodbc`'s connection function is `connect`, not `Connection`. Using the wrong method name will result in instrumentation failing silently or partially.
fix
Always verify the exact name of the connection function for your specific DBAPI driver by checking its documentation or source code. Use the correct string in the `trace_integration` or `wrap_connect` call.
affects: All versions
gotchaThe `sqlcommenter` feature, which enriches SQL queries with OpenTelemetry context for better database-side observability, is disabled by default. If not explicitly enabled, trace context will not be appended to SQL queries, hindering end-to-end trace correlation if the database logs are consumed by an observability backend.
fix
Enable `sqlcommenter` by setting `enable_commenter=True` in the `trace_integration` or `wrap_connect` call: `trace_integration(module, 'connect', 'database_system', enable_commenter=True)`. Further configuration can be done via `commenter_options`.
affects: All versions
gotchaWhen using pre-forking servers (e.g., Gunicorn with multiple workers), OpenTelemetry automatic instrumentation, especially for metrics, can lead to inconsistencies. The forking process can create issues with background threads and locks in SDK components like `PeriodicExportingMetricReader`, potentially causing missing or incorrect metrics.
fix
Consider deploying with a single worker for metrics, or explore programmatic instrumentation specifically for metrics in a multi-worker setup. Alternatively, use workarounds like Prometheus with direct OTLP export, as detailed in OpenTelemetry Python troubleshooting guides.
affects: All versions
gotchaIn some older versions (e.g., `0.53b1`), the `opentelemetry-instrumentation-dbapi` might not correctly respect the `suppress_instrumentation` context manager. This can lead to spans being generated even when you intend to suppress them.
fix
Ensure you are using a recent version of `opentelemetry-instrumentation-dbapi` where this issue has been addressed. As of `0.61b0`, this should be resolved. If upgrading is not an option, verify generated spans thoroughly and apply alternative suppression logic if necessary.
affects: <=0.53b1 (fix introduced in #3460)
breakingThe `TracerProvider.from_resource_attributes` class method was removed in `opentelemetry-sdk` version `1.15.0`. This is a breaking API change that requires updating how `TracerProvider` instances are created, from using a class method to directly passing the resource to the constructor. This highlights a general risk of breaking API changes in core OpenTelemetry Python SDK packages before their `1.0.0` stable release.
fix
Update `TracerProvider` instantiation from `TracerProvider.from_resource_attributes(resource)` to `TracerProvider(resource=resource)`. Regularly review the `opentelemetry-sdk` CHANGELOG for specific API changes and adapt your code accordingly. Pin major versions of OpenTelemetry packages in `requirements.txt` to mitigate unexpected breaking changes.
affects: opentelemetry-sdk >= 1.15.0 (when using older API methods)
Upgrade
Version history
0.63b1latest on PyPI
Audit
Dependencies
opentelemetry-apirequiredRequired for OpenTelemetry API interfaces (e.g., TracerProvider).
opentelemetry-sdkrequiredRequired for OpenTelemetry SDK components (e.g., TracerProvider implementation, SpanProcessor, Exporter).
Python DBAPI 2.0 compliant driverrequiredThis instrumentation wraps existing database drivers (e.g., psycopg2, mysql-connector-python). One must be installed separately.
Agent activity
13 hits · last 30 days
node
4
ahrefsbot
2
googlebot
1
seranking-bot
1
Resources