OpenTelemetry MySQL Instrumentation
The `opentelemetry-instrumentation-mysql` library provides automatic instrumentation for MySQL database operations in Python applications, specifically supporting the `mysql-connector-python` library. It enables the automatic collection of trace data from database interactions, allowing for observability into distributed systems. The library is part of the OpenTelemetry Python Contrib repository and is actively maintained, with releases typically aligning with the broader OpenTelemetry Python SDK and instrumentation updates. The current version is 0.62b0.
Warnings
- gotcha Enabling SQLCommenter (via `enable_commenter=True` in `instrument()`) with MySQL cursors initialized with `prepared=True` can severely degrade performance. This is because SQLCommenter makes statements unique, forcing the database to re-prepare them.
- deprecated MySQL Connector/Python versions 8.1.0 through 8.4.0 included an `[opentelemetry]` extra for `pip install`. Using this extra was not recommended as it installed bundled OpenTelemetry SDK/API libraries, which could lead to dependency conflicts or unexpected behavior with other OpenTelemetry components.
- gotcha OpenTelemetry semantic conventions, which define attribute names and structures, can evolve. While efforts are made to ensure backward compatibility, changes in semantic conventions might affect existing dashboards or alerts. New versions might require setting the `OTEL_SEMCONV_STABILITY_OPT_IN` environment variable to emit both old and stable semantic conventions during a migration period.
Install
-
pip install opentelemetry-instrumentation-mysql
Imports
- MySQLInstrumentor
from opentelemetry.instrumentation.mysql import MySQLInstrumentor
Quickstart
import os
import mysql.connector
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.mysql import MySQLInstrumentor
# 1. Configure OpenTelemetry SDK
resource = Resource.create({"service.name": "mysql-instrumentation-example"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
# 2. Enable MySQL instrumentation
MySQLInstrumentor().instrument()
# 3. Use mysql.connector as usual
# Replace with your actual MySQL connection details
# For a runnable example, you might need a local MySQL server or Docker setup
# Environment variables are used for security and flexibility
DB_HOST = os.environ.get('MYSQL_HOST', 'localhost')
DB_USER = os.environ.get('MYSQL_USER', 'root')
DB_PASSWORD = os.environ.get('MYSQL_PASSWORD', 'password')
DB_NAME = os.environ.get('MYSQL_DATABASE', 'testdb')
try:
# Establish a connection
conn = mysql.connector.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME
)
cursor = conn.cursor()
# Example: Create a table
cursor.execute("DROP TABLE IF EXISTS test_table")
cursor.execute("CREATE TABLE test_table (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))")
# Example: Insert data
cursor.execute("INSERT INTO test_table (name) VALUES (%s)", ("Alice",))
conn.commit()
# Example: Select data
cursor.execute("SELECT * FROM test_table")
result = cursor.fetchall()
print(f"Query Result: {result}")
cursor.close()
conn.close()
print("MySQL operations completed and traces should be visible in console.")
except mysql.connector.Error as err:
print(f"MySQL Error: {err}")
print("Please ensure MySQL server is running and connection details are correct. You might need to install mysql-connector-python (pip install mysql-connector-python).")
finally:
# Ensure the provider is shut down to export any remaining spans
provider.shutdown()