|
| 1 | +import os |
| 2 | +import time |
| 3 | + |
| 4 | +from opentelemetry import trace |
| 5 | +from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter |
| 6 | +from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor |
| 7 | +from opentelemetry.sdk.trace import TracerProvider |
| 8 | +from opentelemetry.sdk.trace.export import ( |
| 9 | + BatchExportSpanProcessor, |
| 10 | + ConsoleSpanExporter, |
| 11 | + SimpleExportSpanProcessor, |
| 12 | +) |
| 13 | + |
| 14 | +# Set up OpenTelemetry tracing |
| 15 | +trace.set_tracer_provider(TracerProvider()) |
| 16 | +trace.get_tracer_provider().add_span_processor( |
| 17 | + SimpleExportSpanProcessor(ConsoleSpanExporter()) |
| 18 | +) |
| 19 | +trace.get_tracer_provider().add_span_processor( |
| 20 | + BatchExportSpanProcessor(CloudTraceSpanExporter(), schedule_delay_millis=5000) |
| 21 | +) |
| 22 | + |
| 23 | +# Trace postgres queries as well |
| 24 | +Psycopg2Instrumentor().instrument() |
| 25 | + |
| 26 | +import psycopg2 |
| 27 | +from google.cloud.sqlcommenter.psycopg2.extension import CommenterCursorFactory |
| 28 | + |
| 29 | +tracer = trace.get_tracer(__name__) |
| 30 | + |
| 31 | + |
| 32 | +def main(): |
| 33 | + cursor_factory = CommenterCursorFactory( |
| 34 | + with_db_driver=True, |
| 35 | + with_dbapi_level=True, |
| 36 | + with_dbapi_threadsafety=True, |
| 37 | + with_driver_paramstyle=True, |
| 38 | + with_libpq_version=True, |
| 39 | + with_opentelemetry=True, |
| 40 | + ) |
| 41 | + conn = psycopg2.connect( |
| 42 | + os.environ["POSTGRES_DSN"], |
| 43 | + cursor_factory=cursor_factory, |
| 44 | + ) |
| 45 | + |
| 46 | + with tracer.start_as_current_span("create data"): |
| 47 | + with conn, conn.cursor() as cursor: |
| 48 | + table_exists = True |
| 49 | + with tracer.start_as_current_span("check if table exists"): |
| 50 | + try: |
| 51 | + cursor.execute('SELECT 1 FROM "names"') |
| 52 | + except psycopg2.DatabaseError: |
| 53 | + table_exists = False |
| 54 | + with conn, conn.cursor() as cursor: |
| 55 | + if not table_exists: |
| 56 | + with tracer.start_as_current_span("create_table"): |
| 57 | + cursor.execute("CREATE TABLE names (name text PRIMARY KEY)") |
| 58 | + cursor.execute( |
| 59 | + """ |
| 60 | + INSERT INTO "names" VALUES |
| 61 | + ('John'), ('Jane'), ('Jess') |
| 62 | + """ |
| 63 | + ) |
| 64 | + |
| 65 | + for _ in range(10000): |
| 66 | + with tracer.start_as_current_span("send postgres query"): |
| 67 | + with conn.cursor() as cursor: |
| 68 | + cursor.execute("SELECT * FROM names") |
| 69 | + time.sleep(0.5) |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + main() |
0 commit comments