OpenTelemetry Psycopg Instrumentation

0.62b0 · active · verified Fri Apr 10

This library provides OpenTelemetry automatic instrumentation for the `psycopg` (PostgreSQL driver, version 3.x) library, enabling the collection of traces and metrics from database interactions. It is part of the `opentelemetry-python-contrib` repository, with the current version being 0.62b0, and releases typically follow the contrib project's cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instrument `psycopg` globally. It initializes a basic OpenTelemetry setup with a console exporter and then calls `PsycopgInstrumentor().instrument()` to automatically wrap all subsequent `psycopg.connect()` calls and database operations. The example attempts to connect to a PostgreSQL database and execute a simple query, printing any connection errors without halting execution.

import psycopg
from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
import os

# Configure OpenTelemetry TracerProvider
resource = Resource.create({"service.name": "my-psycopg-app"})
tracer_provider = TracerProvider(resource=resource)
span_processor = SimpleSpanProcessor(ConsoleSpanExporter())
tracer_provider.add_span_processor(span_processor)
trace.set_tracer_provider(tracer_provider)

# Instrument psycopg connections globally
PsycopgInstrumentor().instrument()

# Connect to a dummy database and perform an operation
try:
    # Replace with your actual connection string or environment variables
    # For demonstration, we'll try a local connection that might fail if no postgres is running
    db_name = os.environ.get('PG_DB_NAME', 'test_db')
    db_user = os.environ.get('PG_DB_USER', 'postgres')
    db_password = os.environ.get('PG_DB_PASSWORD', 'mysecretpassword')
    db_host = os.environ.get('PG_DB_HOST', 'localhost')

    # Note: This connection might fail if a PostgreSQL instance isn't available.
    # The instrumentation will still attempt to trace the 'connect' call.
    conn = psycopg.connect(
        host=db_host,
        user=db_user,
        password=db_password,
        dbname=db_name
    )
    cursor = conn.cursor()
    cursor.execute("SELECT 1;")
    result = cursor.fetchone()
    print(f"Database query result: {result}")
    cursor.close()
    conn.close()
except psycopg.OperationalError as e:
    print(f"Could not connect to PostgreSQL or execute query: {e}")
    print("Please ensure a PostgreSQL instance is running and accessible.")

print("Psycopg operations (attempted) have been instrumented.")

view raw JSON →