Registry /
observability / opentelemetry-instrumentation-psycopg2
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.
Install & Compatibility
Where this runs
tested against v0.63b1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
py 3.10
9/10 runs
9/10 runs
py 3.11
9/10 runs
9/10 runs
py 3.12
9/10 runs
9/10 runs
py 3.13
9/10 runs
9/10 runs
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Psycopg2Instrumentor
✓ from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor
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.
import psycopg2
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.psycopg2 import Psycopg2Instrumentor
import os
# Configure OpenTelemetry SDK
resource = Resource.create({"service.name": "my-psycopg2-app"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
# Instrument psycopg2
# Pass enable_commenter=True and enable_attribute_commenter=True for SQL Commenter support
# Psycopg2Instrumentor().instrument(enable_commenter=True, enable_attribute_commenter=True, skip_dep_check=True)
Psycopg2Instrumentor().instrument()
# Database connection details (use environment variables or sensible defaults for quickstart)
db_name = os.environ.get('POSTGRES_DB', 'testdb')
db_user = os.environ.get('POSTGRES_USER', 'user')
db_password = os.environ.get('POSTGRES_PASSWORD', 'password')
db_host = os.environ.get('POSTGRES_HOST', 'localhost')
db_port = os.environ.get('POSTGRES_PORT', '5432')
try:
# Connect to PostgreSQL
conn = psycopg2.connect(dbname=db_name, user=db_user, password=db_password, host=db_host, port=db_port)
cursor = conn.cursor()
# Execute some SQL queries
with trace.get_tracer(__name__).start_as_current_span("db_operations"):
cursor.execute("CREATE TABLE IF NOT EXISTS otel_test (id serial PRIMARY KEY, name VARCHAR(255))")
cursor.execute("INSERT INTO otel_test (name) VALUES (%s)", ("OpenTelemetry",))
cursor.execute("SELECT * FROM otel_test")
result = cursor.fetchall()
print(f"Fetched result: {result}")
conn.commit()
cursor.close()
conn.close()
print("Database operations completed and traces should be visible.")
except Exception as e:
print(f"An error occurred: {e}")
print("Please ensure a PostgreSQL database is running and accessible (e.g., via Docker):")
print("docker run --rm --name some-postgres -e POSTGRES_DB=testdb -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres")
Debug
Known issues
breakingIncluding SQLCommenter in the `db.statement` span attribute became opt-in from OpenTelemetry Python Contrib version 1.29.0/0.50b0.fixTo include SQLCommenter in the `db.statement` attribute, explicitly set `enable_attribute_commenter=True` when calling `Psycopg2Instrumentor().instrument()`.
affects: >=1.29.0/0.50b0
gotchaEnabling 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.fixEvaluate 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. affects: All versions with SQLCommenter support
gotchaRecursive tracing issues can occur when using `psycopg2.pool.ThreadedConnectionPool` with Python versions earlier than 3.9.fixUpgrade your Python environment to 3.9 or higher to mitigate this issue. If upgrading is not possible, avoid using `ThreadedConnectionPool` with this instrumentation.
affects: <3.9
gotchaFrom 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`.fixAlways 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.
affects: >=1.32.0/0.53b0
gotchaUsing `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.fixAvoid using multiple instrumentation libraries for the same underlying component. If you must, ensure to test thoroughly and potentially disable one of the instrumentations.
affects: All versions
gotchaThe 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.fixEnsure 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`.
affects: All versions
gotchaThe 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.fixEnsure 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`.
affects: All versions
Audit
Dependencies
psycopg2-binaryrequiredRuntime dependency for database connectivity, or 'psycopg2' for a source distribution.
opentelemetry-apirequiredCore OpenTelemetry API for defining telemetry.
opentelemetry-sdkrequiredCore OpenTelemetry SDK for processing and exporting telemetry.