OpenTelemetry pymssql Instrumentation

0.62b0 · active · verified Thu Apr 16

This library provides OpenTelemetry instrumentation for `pymssql`, a Python wrapper for FreeTDS that enables interaction with Microsoft SQL Server. It automatically creates spans for database connection and query operations, helping to trace SQL interactions within your application. The current version is 0.62b0, and it's released as part of the `opentelemetry-python-contrib` project, which has a frequent release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up OpenTelemetry with `pymssql` instrumentation. It configures a basic `TracerProvider` with a `ConsoleSpanExporter`, instruments `pymssql`, and then performs a sample database connection and query. Remember to replace placeholder credentials or set corresponding environment variables for a runnable example.

import os
import pymssql
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.pymssql import PymssqlInstrumentor

# 1. Configure OpenTelemetry Tracer Provider
resource = Resource.create({"service.name": "pymssql-example"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# 2. Instrument pymssql
PymssqlInstrumentor().instrument()

# 3. Use pymssql normally
# Replace with your actual MSSQL connection details or use environment variables
server = os.environ.get("MSSQL_SERVER", "your_server.database.windows.net")
user = os.environ.get("MSSQL_USER", "your_username")
password = os.environ.get("MSSQL_PASSWORD", "your_password")
database = os.environ.get("MSSQL_DATABASE", "your_database")

if not all([server, user, password, database]):
    print("WARNING: Skipping pymssql connection as environment variables for MSSQL_SERVER, MSSQL_USER, MSSQL_PASSWORD, MSSQL_DATABASE are not set.")
    print("Please set these to run the quickstart.")
else:
    print(f"Attempting to connect to MSSQL: {server}/{database} with user {user}...")
    try:
        with pymssql.connect(server, user, password, database) as conn:
            with conn.cursor() as cursor:
                cursor.execute('SELECT 1 as result')
                row = cursor.fetchone()
                print(f"Query result: {row}")
        print("pymssql connection and query successful (and instrumented!). Check console for OTel traces.")
    except Exception as e:
        print(f"Error connecting to or querying MSSQL: {e}")
        print("Ensure MSSQL server is accessible and credentials are correct.")

view raw JSON →