OpenTelemetry MySQL Instrumentation

0.62b0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to enable OpenTelemetry MySQL instrumentation and perform basic database operations. It sets up a simple `TracerProvider` with a `ConsoleSpanExporter` to print traces to the console. You must have `mysql-connector-python` installed and a running MySQL server with the specified connection details (or environment variables) for the example to work.

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()

view raw JSON →