{"id":2642,"library":"opentelemetry-instrumentation-psycopg","title":"OpenTelemetry Psycopg Instrumentation","description":"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.","status":"active","version":"0.62b0","language":"en","source_language":"en","source_url":"https://github.com/open-telemetry/opentelemetry-python-contrib","tags":["opentelemetry","observability","tracing","database","psycopg","postgresql"],"install":[{"cmd":"pip install opentelemetry-instrumentation-psycopg","lang":"bash","label":"Install package"}],"dependencies":[{"reason":"The PostgreSQL driver being instrumented. Requires psycopg version 3.1.0 or higher.","package":"psycopg","optional":false},{"reason":"Required for a full OpenTelemetry setup (e.g., configuring exporters, resource detectors). While not a direct install dependency of this specific instrumentation, it is essential for end-to-end tracing.","package":"opentelemetry-sdk","optional":false}],"imports":[{"symbol":"PsycopgInstrumentor","correct":"from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor"}],"quickstart":{"code":"import psycopg\nfrom opentelemetry.instrumentation.psycopg import PsycopgInstrumentor\nfrom opentelemetry import trace\nfrom opentelemetry.sdk.resources import Resource\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor\nimport os\n\n# Configure OpenTelemetry TracerProvider\nresource = Resource.create({\"service.name\": \"my-psycopg-app\"})\ntracer_provider = TracerProvider(resource=resource)\nspan_processor = SimpleSpanProcessor(ConsoleSpanExporter())\ntracer_provider.add_span_processor(span_processor)\ntrace.set_tracer_provider(tracer_provider)\n\n# Instrument psycopg connections globally\nPsycopgInstrumentor().instrument()\n\n# Connect to a dummy database and perform an operation\ntry:\n    # Replace with your actual connection string or environment variables\n    # For demonstration, we'll try a local connection that might fail if no postgres is running\n    db_name = os.environ.get('PG_DB_NAME', 'test_db')\n    db_user = os.environ.get('PG_DB_USER', 'postgres')\n    db_password = os.environ.get('PG_DB_PASSWORD', 'mysecretpassword')\n    db_host = os.environ.get('PG_DB_HOST', 'localhost')\n\n    # Note: This connection might fail if a PostgreSQL instance isn't available.\n    # The instrumentation will still attempt to trace the 'connect' call.\n    conn = psycopg.connect(\n        host=db_host,\n        user=db_user,\n        password=db_password,\n        dbname=db_name\n    )\n    cursor = conn.cursor()\n    cursor.execute(\"SELECT 1;\")\n    result = cursor.fetchone()\n    print(f\"Database query result: {result}\")\n    cursor.close()\n    conn.close()\nexcept psycopg.OperationalError as e:\n    print(f\"Could not connect to PostgreSQL or execute query: {e}\")\n    print(\"Please ensure a PostgreSQL instance is running and accessible.\")\n\nprint(\"Psycopg operations (attempted) have been instrumented.\")\n","lang":"python","description":"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."},"warnings":[{"fix":"Review `opentelemetry-python-contrib` release notes (CHANGELOG.md) regularly when upgrading and be prepared for potential adjustments to your code or configuration.","message":"As a beta package (`b0` suffix), `opentelemetry-instrumentation-psycopg` is subject to breaking changes without prior deprecation periods. APIs and behaviors may evolve with future releases.","severity":"gotcha","affected_versions":"All `b0` versions"},{"fix":"If you relied on SQL comments being present in `db.statement`, you must explicitly enable them during instrumentation setup by passing `enable_commenter=True` to the `instrument()` method: `PsycopgInstrumentor().instrument(enable_commenter=True)`.","message":"Including SQL comments (like traceparent) directly within the `db.statement` span attribute became opt-in as of `opentelemetry-python-contrib` version 1.29.0/0.50b0. Previously, it might have been included by default.","severity":"breaking","affected_versions":">=1.29.0/0.50b0 of `opentelemetry-python-contrib` (which includes this instrumentation)"},{"fix":"Test thoroughly with your specific `psycopg` and pooling library versions. Refer to `opentelemetry-python-contrib` GitHub issues for known pooling-related problems. Ensure your Python environment meets `psycopg`'s and OpenTelemetry's minimum requirements (Python >=3.9 for this instrumentation and `psycopg` >=3.1.0).","message":"When using `psycopg` connection pooling, ensure compatibility with the OpenTelemetry instrumentation. While specific issues were reported for `psycopg2` and Python versions 3.6-3.8 leading to recursion errors with `ThreadedConnectionPool`, general complexities can arise with any pooling setup. Ensure your `psycopg` version (3.1.0+) and Python version (3.9+) meet requirements.","severity":"gotcha","affected_versions":"All versions, especially with connection pooling"}],"env_vars":null,"last_verified":"2026-04-10T00:00:00.000Z","next_check":"2026-07-09T00:00:00.000Z"}