{"id":909,"library":"opentelemetry-instrumentation-psycopg2","title":"OpenTelemetry Psycopg2 Instrumentation","description":"This library provides automatic instrumentation for the `psycopg2` PostgreSQL adapter, enabling OpenTelemetry tracing for database operations within Python applications. It is part of the broader `opentelemetry-python-contrib` project, which sees frequent updates for bug fixes, new features, and compatibility with various libraries. The current version is 0.61b0 and it requires Python >=3.9.","status":"active","version":"0.61b0","language":"python","source_language":"en","source_url":"https://github.com/open-telemetry/opentelemetry-python-contrib","tags":["opentelemetry","observability","tracing","database","psycopg2","postgresql"],"install":[{"cmd":"pip install opentelemetry-instrumentation-psycopg2 psycopg2-binary","lang":"bash","label":"Install with psycopg2-binary"},{"cmd":"pip install opentelemetry-distro opentelemetry-exporter-otlp","lang":"bash","label":"Install base OTel packages (if not already)"}],"dependencies":[{"reason":"Runtime dependency for database connectivity, or 'psycopg2' for a source distribution.","package":"psycopg2-binary","optional":false},{"reason":"Core OpenTelemetry API for defining telemetry.","package":"opentelemetry-api","optional":false},{"reason":"Core OpenTelemetry SDK for processing and exporting telemetry.","package":"opentelemetry-sdk","optional":false}],"imports":[{"symbol":"Psycopg2Instrumentor","correct":"from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor"}],"quickstart":{"code":"import psycopg2\nfrom opentelemetry import trace\nfrom opentelemetry.sdk.resources import Resource\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor\nfrom opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor\nimport os\n\n# Configure OpenTelemetry SDK\nresource = Resource.create({\"service.name\": \"my-psycopg2-app\"})\nprovider = TracerProvider(resource=resource)\nprocessor = SimpleSpanProcessor(ConsoleSpanExporter())\nprovider.add_span_processor(processor)\ntrace.set_tracer_provider(provider)\n\n# Instrument psycopg2\n# Pass enable_commenter=True and enable_attribute_commenter=True for SQL Commenter support\n# Psycopg2Instrumentor().instrument(enable_commenter=True, enable_attribute_commenter=True, skip_dep_check=True)\nPsycopg2Instrumentor().instrument()\n\n# Database connection details (use environment variables or sensible defaults for quickstart)\ndb_name = os.environ.get('POSTGRES_DB', 'testdb')\ndb_user = os.environ.get('POSTGRES_USER', 'user')\ndb_password = os.environ.get('POSTGRES_PASSWORD', 'password')\ndb_host = os.environ.get('POSTGRES_HOST', 'localhost')\ndb_port = os.environ.get('POSTGRES_PORT', '5432')\n\ntry:\n    # Connect to PostgreSQL\n    conn = psycopg2.connect(dbname=db_name, user=db_user, password=db_password, host=db_host, port=db_port)\n    cursor = conn.cursor()\n\n    # Execute some SQL queries\n    with trace.get_tracer(__name__).start_as_current_span(\"db_operations\"):\n        cursor.execute(\"CREATE TABLE IF NOT EXISTS otel_test (id serial PRIMARY KEY, name VARCHAR(255))\")\n        cursor.execute(\"INSERT INTO otel_test (name) VALUES (%s)\", (\"OpenTelemetry\",))\n        cursor.execute(\"SELECT * FROM otel_test\")\n        result = cursor.fetchall()\n        print(f\"Fetched result: {result}\")\n\n    conn.commit()\n    cursor.close()\n    conn.close()\n    print(\"Database operations completed and traces should be visible.\")\nexcept Exception as e:\n    print(f\"An error occurred: {e}\")\n    print(\"Please ensure a PostgreSQL database is running and accessible (e.g., via Docker):\")\n    print(\"docker run --rm --name some-postgres -e POSTGRES_DB=testdb -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres\")\n","lang":"python","description":"This quickstart demonstrates how to instrument `psycopg2` to automatically generate traces for database interactions. It configures a simple ConsoleSpanExporter to print traces to the console and performs basic PostgreSQL operations. Ensure you have a PostgreSQL instance running, for example, using Docker."},"warnings":[{"fix":"To include SQLCommenter in the `db.statement` attribute, explicitly set `enable_attribute_commenter=True` when calling `Psycopg2Instrumentor().instrument()`.","message":"Including SQLCommenter in the `db.statement` span attribute became opt-in from OpenTelemetry Python Contrib version 1.29.0/0.50b0.","severity":"breaking","affected_versions":">=1.29.0/0.50b0"},{"fix":"Evaluate the need for SQLCommenter carefully. If enabled, consider using `commenter_options` to opt out of specific key-value pairs (`Psycopg2Instrumentor().instrument(enable_commenter=True, commenter_options={'db_driver': False})`) to control cardinality.","message":"Enabling SQLCommenter (`enable_commenter=True`) can lead to high cardinality in database span attributes if not managed, potentially increasing monitoring costs and reducing performance in some backends.","severity":"gotcha","affected_versions":"All versions with SQLCommenter support"},{"fix":"Upgrade your Python environment to 3.9 or higher to mitigate this issue. If upgrading is not possible, avoid using `ThreadedConnectionPool` with this instrumentation.","message":"Recursive tracing issues can occur when using `psycopg2.pool.ThreadedConnectionPool` with Python versions earlier than 3.9.","severity":"gotcha","affected_versions":"<3.9"},{"fix":"Always ensure `psycopg2` or `psycopg2-binary` is installed alongside `opentelemetry-instrumentation-psycopg2`. In rare cases, `skip_dep_check=True` can be passed to `instrument()` if you manage dependencies manually or encounter unexpected issues with multiple `psycopg` distributions.","message":"From OpenTelemetry Python Contrib version 1.32.0/0.53b0, instrumentors perform lazy-import dependency checks. If the underlying `psycopg2` (or `psycopg2-binary`) package is missing, `instrument()` might raise an `ImportError`.","severity":"gotcha","affected_versions":">=1.32.0/0.53b0"},{"fix":"Avoid using multiple instrumentation libraries for the same underlying component. If you must, ensure to test thoroughly and potentially disable one of the instrumentations.","message":"Using `opentelemetry-instrumentation-psycopg2` alongside other APM or tracing libraries that also instrument `psycopg2` can lead to conflicts, duplicate traces, or prevent database queries from being collected.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure a PostgreSQL database server is running and accessible at the specified host and port. For example, use Docker to run a PostgreSQL instance as shown in the test output's suggestion: `docker run --rm --name some-postgres -e POSTGRES_DB=testdb -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres`.","message":"The instrumentation requires a running and accessible PostgreSQL database server to connect to. Failures such as 'Connection refused' indicate an environmental issue with the database setup, not a problem with the instrumentation library itself.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure a PostgreSQL database is running and accessible from the environment where the application is executed. For example, use a Docker container: `docker run --rm --name some-postgres -e POSTGRES_DB=testdb -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres`.","message":"The instrumentation requires a running PostgreSQL database instance to connect to. A 'Connection refused' error indicates that the database server is not accessible at the specified host and port.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"search_vec":"'0.61':52 '3.9':58 'adapt':13 'applic':22 'automat':7 'b0':53 'broader':28 'bug':39 'compat':44 'contrib':32 'current':49 'databas':18,62 'enabl':14 'featur':42 'fix':40 'frequent':36 'instrument':3,8 'librari':5,47 'new':41 'observ':60 'opentelemetri':1,15,30,59 'opentelemetry-python-contrib':29 'oper':19 'part':25 'postgresql':12,64 'project':33 'provid':6 'psycopg2':2,11,63 'python':21,31,57 'requir':56 'see':35 'trace':16,61 'updat':37 'various':46 'version':50 'within':20","created_at":"2026-03-29T06:07:15.798324+00:00","updated_at":"2026-04-16T17:43:10.775933+00:00","problems":{"verify_error":"error: Failed to parse: `opentelemetry-instrumentation-psycopg2 psycopg2-binary`\n  Caused by: Expected one of `@`, `(`, `<`, `=`, `>`, `~`, `!`, `;`, found `p`\nopentelemetry-instrumentation-psycopg2 psycopg2-binary\n                                       ^"},"ecosystem":"pypi","meta_description":null,"install_score":100,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.63b1","cli_name":"","cli_version":null,"type":"library","homepage":"https://opentelemetry.io","github":"https://github.com/open-telemetry/opentelemetry-python-contrib","docs":null,"changelog":null,"pypi":"https://pypi.org/project/opentelemetry-instrumentation-psycopg2/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["observability","database"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"install_fail","verified_at":"2026-06-28","last_verified":"2026-06-28","next_check":"2026-07-05","install_tag":"verified"}}