Registry /
observability / opentelemetry-instrumentation-mysqlclient
Install & Compatibility
Where this runs
tested against v0.65b0 · 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
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
MySQLClientInstrumentor
✓ from opentelemetry.instrumentation.mysqlclient import MySQLClientInstrumentor
✗ from opentelemetry.instrumentation.mysqlclient import MySQLClientInstrumentor
This quickstart demonstrates how to initialize the OpenTelemetry SDK, instrument `mysqlclient`, and perform basic database operations. The `MySQLClientInstrumentor().instrument()` call patches the `mysqlclient` library to automatically create spans for database interactions. Traces are then exported to the console. Remember to replace placeholder database credentials with your actual ones, ideally via environment variables, and configure a proper exporter for production use.
import os
import MySQLdb
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, BatchSpanProcessor
from opentelemetry.instrumentation.mysqlclient import MySQLClientInstrumentor
# 1. Configure OpenTelemetry Tracer Provider
resource = Resource.create({"service.name": "mysqlclient-app"})
provider = TracerProvider(resource=resource)
span_processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(span_processor)
trace.set_tracer_provider(provider)
# 2. Instrument mysqlclient
# Optional: enable_commenter=True for SQLCommenter support
# MySQLClientInstrumentor().instrument(enable_commenter=True)
MySQLClientInstrumentor().instrument()
# 3. Use mysqlclient as usual
DB_HOST = os.environ.get('MYSQL_HOST', 'localhost')
DB_USER = os.environ.get('MYSQL_USER', 'root')
DB_PASSWORD = os.environ.get('MYSQL_PASSWORD', 'password') # Use environment variables for auth
DB_NAME = os.environ.get('MYSQL_DB', 'test_db')
try:
# Wrap database operations within a span for clearer context
with trace.get_tracer(__name__).start_as_current_span("db_operations"):
cnx = MySQLdb.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME
)
cursor = cnx.cursor()
# Example DDL and DML operations
cursor.execute("DROP TABLE IF EXISTS test_table")
cursor.execute("CREATE TABLE test_table (id INT, name VARCHAR(255))")
cursor.execute("INSERT INTO test_table (id, name) VALUES (1, 'OpenTelemetry')")
cnx.commit()
cursor.execute("SELECT * FROM test_table")
for row in cursor.fetchall():
print(f"Fetched: {row}")
cursor.close()
cnx.close()
print("MySQL operations completed successfully and should be traced.")
except MySQLdb.Error as err:
print(f"Error: {err}")
current_span = trace.get_current_span()
current_span.record_exception(err)
current_span.set_status(trace.Status(trace.StatusCode.ERROR, description=str(err)))
finally:
# Ensure exporter is shut down to flush any buffered spans
provider.shutdown()
opentelemetry-instrument --version
Debug
Known issues
breakingThe inclusion of SQLCommenter data in the `db.statement` span attribute became opt-in. This was a breaking change introduced around OpenTelemetry Python Contrib v0.49b0 / OpenTelemetry Python SDK v1.28.0.fixIf you relied on sqlcommenter data appearing in `db.statement`, you must explicitly enable it by passing `enable_attribute_commenter=True` to the `instrument()` method: `MySQLClientInstrumentor().instrument(enable_commenter=True, enable_attribute_commenter=True)`.
affects: >=0.49b0
gotchaEnabling SQLCommenter (`enable_commenter=True`) can cause severe performance penalties if you are using `mysqlclient` cursors with `prepared=True` (prepared statements). SQLCommenter appends unique comments to queries, effectively defeating the purpose of prepared statements by making each query unique, forcing re-preparation by the database.fixAvoid using `enable_commenter=True` when `prepared=True` cursors are in use. If `prepared=True` is critical, consider disabling SQLCommenter. If `prepared=False` (the default) is acceptable, SQLCommenter can be used without this penalty.
affects: All versions where SQLCommenter is available.
gotchaThis instrumentation typically requires `mysqlclient` versions less than 3 for full compatibility. Check the `requires_dist` metadata on PyPI or the `opentelemetry-python-contrib` documentation for the exact compatible version range.fixEnsure your `mysqlclient` dependency is within the compatible range, often specified as `<3.0.0` to avoid potential breaking changes in major `mysqlclient` releases.
affects: All versions
gotchaOpenTelemetry Semantic Conventions are continually evolving. Older versions of instrumentations might emit deprecated attributes. Future major versions of OpenTelemetry Python or its instrumentations may switch to new semantic conventions by default, which can break analysis tools if not configured correctly.fixStay up-to-date with OpenTelemetry documentation. Use the `OTEL_SEMCONV_STABILITY_OPT_IN` environment variable (e.g., `OTEL_SEMCONV_STABILITY_OPT_IN=http/dup,database/dup`) to emit both old and new semantic conventions during migration periods, ensuring compatibility with your observability backend and dashboards. Consult the official OpenTelemetry Python migration guides for detailed instructions.
affects: All versions
Upgrade
Version history
0.65b0latest on PyPI · released Jul 16, 2026
Audit
Dependencies
mysqlclientrequiredThe database driver being instrumented. Specific versions may be required for full compatibility.
opentelemetry-sdkrequiredProvides the core OpenTelemetry SDK components (TracerProvider, SpanProcessors, etc.)
opentelemetry-apirequiredProvides the OpenTelemetry API interfaces.