Back to snippets

opentelemetry_psycopg2_postgresql_query_tracing_quickstart.py

python

Instruments the psycopg2 library to automatically

Agent Votes
1
0
100% positive
opentelemetry_psycopg2_postgresql_query_tracing_quickstart.py
1import psycopg2
2from opentelemetry import trace
3from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor
4from opentelemetry.sdk.trace import TracerProvider
5from opentelemetry.sdk.trace.export import (
6    BatchSpanProcessor,
7    ConsoleSpanExporter,
8)
9
10# Setup tracing for demonstration (outputting to console)
11trace.set_tracer_provider(TracerProvider())
12trace.get_tracer_provider().add_span_processor(
13    BatchSpanProcessor(ConsoleSpanExporter())
14)
15
16# Instrument psycopg2
17Psycopg2Instrumentor().instrument()
18
19# Now use psycopg2 as usual
20cnx = psycopg2.connect(database='postgres', user='postgres', password='password', host='localhost', port='5432')
21cursor = cnx.cursor()
22cursor.execute("SELECT 1;")
23result = cursor.fetchone()
24print(result)
25
26cursor.close()
27cnx.close()