pythonpsycopg2jaegeropen-telemetrydistributed-tracing

OpenTelemetry is not tracing SQL Statements while using cursor_factory as NamedTupleCursor


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```

Solution

  • 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