{"id":2161,"library":"opentelemetry-instrumentation-mysqlclient","title":"OpenTelemetry mysqlclient Instrumentation","description":"This library provides OpenTelemetry automatic instrumentation for the `mysqlclient` Python package, enabling tracing of database operations. It is part of the `opentelemetry-python-contrib` project, which maintains various community-contributed instrumentations. The current version is 0.62b0, and releases generally align with the `opentelemetry-python` core and contrib release cadence, often in beta stages.","status":"active","version":"0.62b0","language":"en","source_language":"en","source_url":"https://github.com/open-telemetry/opentelemetry-python-contrib","tags":["opentelemetry","observability","tracing","mysql","mysqlclient","instrumentation","database"],"install":[{"cmd":"pip install opentelemetry-instrumentation-mysqlclient","lang":"bash","label":"Install `mysqlclient` instrumentation"},{"cmd":"pip install mysqlclient","lang":"bash","label":"Install the underlying `mysqlclient` library"},{"cmd":"pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http","lang":"bash","label":"Install core OpenTelemetry SDK and OTLP Exporter (recommended for full setup)"}],"dependencies":[{"reason":"The database driver being instrumented. Specific versions may be required for full compatibility.","package":"mysqlclient","optional":false},{"reason":"Provides the core OpenTelemetry SDK components (TracerProvider, SpanProcessors, etc.)","package":"opentelemetry-sdk","optional":false},{"reason":"Provides the OpenTelemetry API interfaces.","package":"opentelemetry-api","optional":false}],"imports":[{"symbol":"MySQLClientInstrumentor","correct":"from opentelemetry.instrumentation.mysqlclient import MySQLClientInstrumentor"}],"quickstart":{"code":"import os\nimport MySQLdb\nfrom opentelemetry import trace\nfrom opentelemetry.sdk.resources import Resource\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import ConsoleSpanExporter, BatchSpanProcessor\nfrom opentelemetry.instrumentation.mysqlclient import MySQLClientInstrumentor\n\n# 1. Configure OpenTelemetry Tracer Provider\nresource = Resource.create({\"service.name\": \"mysqlclient-app\"})\nprovider = TracerProvider(resource=resource)\nspan_processor = BatchSpanProcessor(ConsoleSpanExporter())\nprovider.add_span_processor(span_processor)\ntrace.set_tracer_provider(provider)\n\n# 2. Instrument mysqlclient\n# Optional: enable_commenter=True for SQLCommenter support\n# MySQLClientInstrumentor().instrument(enable_commenter=True)\nMySQLClientInstrumentor().instrument()\n\n# 3. Use mysqlclient as usual\nDB_HOST = os.environ.get('MYSQL_HOST', 'localhost')\nDB_USER = os.environ.get('MYSQL_USER', 'root')\nDB_PASSWORD = os.environ.get('MYSQL_PASSWORD', 'password') # Use environment variables for auth\nDB_NAME = os.environ.get('MYSQL_DB', 'test_db')\n\ntry:\n    # Wrap database operations within a span for clearer context\n    with trace.get_tracer(__name__).start_as_current_span(\"db_operations\"):\n        cnx = MySQLdb.connect(\n            host=DB_HOST,\n            user=DB_USER,\n            password=DB_PASSWORD,\n            database=DB_NAME\n        )\n        cursor = cnx.cursor()\n\n        # Example DDL and DML operations\n        cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n        cursor.execute(\"CREATE TABLE test_table (id INT, name VARCHAR(255))\")\n        cursor.execute(\"INSERT INTO test_table (id, name) VALUES (1, 'OpenTelemetry')\")\n        cnx.commit()\n\n        cursor.execute(\"SELECT * FROM test_table\")\n        for row in cursor.fetchall():\n            print(f\"Fetched: {row}\")\n\n        cursor.close()\n        cnx.close()\n    print(\"MySQL operations completed successfully and should be traced.\")\n\nexcept MySQLdb.Error as err:\n    print(f\"Error: {err}\")\n    current_span = trace.get_current_span()\n    current_span.record_exception(err)\n    current_span.set_status(trace.Status(trace.StatusCode.ERROR, description=str(err)))\nfinally:\n    # Ensure exporter is shut down to flush any buffered spans\n    provider.shutdown()","lang":"python","description":"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."},"warnings":[{"fix":"If 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)`.","message":"The 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.","severity":"breaking","affected_versions":">=0.49b0"},{"fix":"Avoid 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.","message":"Enabling 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.","severity":"gotcha","affected_versions":"All versions where SQLCommenter is available."},{"fix":"Ensure your `mysqlclient` dependency is within the compatible range, often specified as `<3.0.0` to avoid potential breaking changes in major `mysqlclient` releases.","message":"This 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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Stay 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.","message":"OpenTelemetry 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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}