1

Kindly look at the code below. I'm using opentelemetry for tracing. Psycopg2Instrumentor for PostgreSQL tracing. Here only the "show server_version" SQL statement is getting traced. But the SQL statement in execute method is not traced. I think it's because of using NamedTupleCursor cursor_factory. If I remove NamedTupleCursor, it's tracing the main SQL statements. Could you please help me to trace the main SQL statement without removing NamedTupleCursor?

def self.get_connection():
   #conn = create_connection()
   with conn.cursor() as curs:
       curs.execute("show server_version") ---> this sql statement is getting tracked
   return conn

def execute()
   with self.get_connection() as conn:
       with conn.cursor(cursor_factory=NamedTupleCursor) as curs:
           curs.execute("Sql statements"). ---> this sql statement is **not** getting tracked```
Raguram Gopi
  • 202
  • 1
  • 2
  • 8
  • Not sure how that would make a difference as the cursor class just affects how the data you retrieve in Python is presented. The query sent to the server will be the same. I would look at the Postgres log directly and see what is actually hitting the server. – Adrian Klaver Mar 15 '22 at 16:28
  • Psycopg2Instrumentor is not tracing the SQL statement, bcoz it extends NamedTupleCursor. @psycopg2 people pls help here. – Raguram Gopi Mar 16 '22 at 12:08
  • I would look at this issue [Psycopg2Instrumentor doesn't work for cursors with non-default cursor_factory](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/578) and add to it. – Adrian Klaver Mar 16 '22 at 14:31
  • Yes, @AdrianKlaver Exactly the same issue. Kindly let me know the solution. – Raguram Gopi Mar 16 '22 at 14:44
  • The solution is to add your comment to the issue and see if you can have the project fix the code. – Adrian Klaver Mar 16 '22 at 14:51

1 Answers1

0

Below is the code snippet for working with Psycopg2Instrumentor for PostgreSQL tracing. The instrumentation code to be updated on passing cursor_factory in cursor parameter, rather than setting it in connection. For now, the below works for me and tracing got captured.

import psycopg2
from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor

Psycopg2Instrumentor().instrument()

#add your cursor factory in connection method
cnx = psycopg2.connect(
        host=host, database=DBname, user=user, password=password, cursor_factory=RealDictCursor)

#remove the cursor factory from cursor method
cursor = cnx.cursor()
cursor.execute("SELECT statement")
cursor.close()
cnx.close()

Thanks to the thread (Psycopg2Instrumentor doesn't work for cursors with non-default cursor_factory) and @RaguramGopi

Daniel Inbaraj
  • 778
  • 8
  • 9