OpenTelemetry aiopg Instrumentation

0.62b0 · active · verified Sat Apr 11

This library provides OpenTelemetry instrumentation for `aiopg`, an async PostgreSQL adapter for asyncio. It allows for automatic tracing of database operations, generating spans and attributes according to OpenTelemetry semantic conventions. It is part of the broader `opentelemetry-python-contrib` project, currently in a beta development status (version 0.62b0), and receives frequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instrument `aiopg` using `AiopgInstrumentor`. It sets up a basic OpenTelemetry `TracerProvider` with a `ConsoleSpanExporter` and then calls `AiopgInstrumentor().instrument()` to enable automatic tracing. Subsequently, any `aiopg` database operations will generate spans. Remember to replace the `ConsoleSpanExporter` with a proper OTLP exporter for production use and provide a valid PostgreSQL DSN via environment variables or directly.

import asyncio
import aiopg
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.aiopg import AiopgInstrumentor
import os

# Configure OpenTelemetry (replace with your actual exporter/provider setup)
resource = Resource.create({"service.name": "aiopg-service"})
provider = TracerProvider(resource=resource)
span_processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(span_processor)
trace.set_tracer_provider(provider)

# Instrument aiopg
AiopgInstrumentor().instrument()

async def fetch_data():
    dsn = os.environ.get('POSTGRES_DSN', 'dbname=test user=postgres password=password host=localhost')
    print(f"Connecting to PostgreSQL with DSN: {dsn}")
    async with aiopg.connect(dsn) as conn:
        async with conn.cursor() as cur:
            await cur.execute("SELECT 1 + 1")
            result = await cur.fetchone()
            print(f"DB Query Result: {result}")

async def main():
    await fetch_data()

if __name__ == "__main__":
    # Ensure PostgreSQL is running and accessible or configure a dummy DSN for testing
    # For a real setup, provide POSTGRES_DSN env var, e.g., 'dbname=yourdb user=youruser password=yourpass host=yourhost'
    asyncio.run(main())

view raw JSON →