OpenTelemetry DBAPI Instrumentation
raw JSON → 0.61b0 verified Tue May 12 auth: no python install: verified
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.
pip install opentelemetry-instrumentation-dbapi opentelemetry-sdk mysql-connector-python Common errors
error ModuleNotFoundError: No module named 'opentelemetry.instrumentation' ↓
cause This error typically occurs when the OpenTelemetry instrumentation packages, including `opentelemetry-instrumentation-dbapi`, are not installed in the Python environment where your application is running, or due to namespace package conflicts.
fix
Ensure all necessary OpenTelemetry packages are installed in the correct environment using
pip install opentelemetry-distro[otlp] opentelemetry-instrumentation-dbapi (or specific instrumentation for your database driver like opentelemetry-instrumentation-psycopg2). If still facing issues, verify the Python environment and check for namespace conflicts. error MySQLdb._exceptions.OperationalError: (2006, '') (database is gone) ↓
cause When using `opentelemetry-instrumentation-dbapi` with `MySQLdb` (or `mysqlclient`), the instrumented connection object might be prematurely closed or appear unusable after being wrapped, leading to this error when database operations are attempted.
fix
This specific issue has been a known bug in older versions of
opentelemetry-instrumentation-dbapi related to how it wrapped MySQLdb connections. Ensure you are using the latest compatible versions of opentelemetry-instrumentation-dbapi and MySQLdb/mysqlclient. If the issue persists, consider using a different MySQL driver if possible, or consult the OpenTelemetry GitHub issues for potential workarounds or newer fixes. error trace_integration(pyodbc, "Connection", "odbc") not tracing ↓
cause The `trace_integration` function requires the *name* of the connect method for the DB-API 2.0 compliant module, not the connection class name. For `pyodbc`, the connect method is typically named `connect`, not `Connection`.
fix
Replace the incorrect connect method name in
trace_integration. For pyodbc, use trace_integration(pyodbc, "connect", "odbc") to correctly instrument the connection. Warnings
breaking OpenTelemetry 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`.
gotcha Incorrectly 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.
gotcha The `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`.
gotcha When 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.
gotcha In 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.
breaking The `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.
Install compatibility verified last tested: 2026-05-12
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 0.25s 27.5M
3.10 alpine (musl) - - 0.26s 27.3M
3.10 slim (glibc) wheel 3.5s 0.18s 89M
3.10 slim (glibc) - - 0.17s 127M
3.11 alpine (musl) wheel - 0.34s 30.5M
3.11 alpine (musl) - - 0.39s 30.3M
3.11 slim (glibc) wheel 3.3s 0.30s 92M
3.11 slim (glibc) - - 0.29s 130M
3.12 alpine (musl) wheel - 0.55s 22.1M
3.12 alpine (musl) - - 0.58s 21.9M
3.12 slim (glibc) wheel 3.0s 0.53s 83M
3.12 slim (glibc) - - 0.54s 121M
3.13 alpine (musl) wheel - 0.18s 21.8M
3.13 alpine (musl) - - 0.19s 21.5M
3.13 slim (glibc) wheel 3.0s 0.19s 83M
3.13 slim (glibc) - - 0.19s 121M
3.9 alpine (musl) wheel - 0.19s 26.5M
3.9 alpine (musl) - - 0.21s 26.3M
3.9 slim (glibc) wheel 4.0s 0.19s 117M
3.9 slim (glibc) - - 0.17s 117M
Imports
- trace_integration wrong
from opentelemetry.instrumentation.dbapi import DbApiInstrumentorcorrectfrom opentelemetry.instrumentation.dbapi import trace_integration
Quickstart last tested: 2026-04-24
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.")