OpenTelemetry PyMySQL Instrumentation

0.62b0 · active · verified Fri Apr 10

This library provides automatic instrumentation for PyMySQL, allowing OpenTelemetry to trace database operations performed via PyMySQL. It is part of the `opentelemetry-python-contrib` repository, which releases frequently (often several times a month) with new features, bug fixes, and instrumentations. The current version is 0.62b0, indicating a beta release.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up the OpenTelemetry Python SDK and enable PyMySQL instrumentation. It configures a simple ConsoleSpanExporter to print traces to the console. When `PyMySQLInstrumentor().enable()` is called, subsequent `pymysql` operations will automatically generate spans. Remember to replace placeholder database credentials with actual ones for a functional setup.

import os
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.pymysql import PyMySQLInstrumentor
import pymysql

# 1. Configure OpenTelemetry SDK
resource = Resource.create({"service.name": "pymysql-example"})
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(tracer_provider)

# 2. Enable PyMySQL Instrumentation
PyMySQLInstrumentor().enable()

# 3. Use PyMySQL (this will be traced)
# For a real application, replace with actual database credentials
try:
    # Use os.environ.get for sensitive info or mock connection
    conn = pymysql.connect(
        host=os.environ.get('MYSQL_HOST', 'localhost'),
        user=os.environ.get('MYSQL_USER', 'root'),
        password=os.environ.get('MYSQL_PASSWORD', 'testpass'),
        database=os.environ.get('MYSQL_DATABASE', 'testdb')
    )
    cursor = conn.cursor()
    cursor.execute("SELECT 1 + 1")
    result = cursor.fetchone()
    print(f"PyMySQL query result: {result}")
    cursor.close()
    conn.close()
except Exception as e:
    print(f"Could not connect to PyMySQL or execute query: {e}")
    print("Make sure a MySQL/MariaDB server is running and accessible with correct credentials.")

print("Traces should be printed to console above.")

view raw JSON →