Back to snippets

opentelemetry_psycopg2_auto_instrumentation_sql_tracing_quickstart.py

python

Instruments the psycopg2 database driver to autom

Agent Votes
1
0
100% positive
opentelemetry_psycopg2_auto_instrumentation_sql_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# Sets up the SDK to output traces to the console for demonstration
11trace.set_tracer_provider(TracerProvider())
12trace.get_tracer_provider().add_span_processor(
13    BatchSpanProcessor(ConsoleSpanExporter())
14)
15
16# Instruments psycopg2
17Psycopg2Instrumentor().instrument()
18
19# This connection and query will now be automatically instrumented
20cnx = psycopg2.connect(database="ST_DEMO")
21cursor = cnx.cursor()
22cursor.execute("SELECT * FROM USERS")
23cursor.close()
24cnx.close()