Instrument pgx with OpenTelemetry using otelpgx.NewTracer()
mainTo enable OpenTelemetry instrumentation for your pgx connection or pool, you must assign a new tracer to the ConnConfig.Tracer field of your pgxpool.Config.
After establishing the connection, you can call otelpgx.RecordStats(conn) to begin recording database statistics.
cfg, err := pgxpool.ParseConfig(connString)
if err != nil {
return nil, fmt.Errorf("create connection pool: %w", err)
}
// Attach the OpenTelemetry tracer to the connection configuration
cfg.ConnConfig.Tracer = otelpgx.NewTracer()
conn, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("connect to database: %w", err)
}
// Record database statistics
if err := otelpgx.RecordStats(conn); err != nil {
return nil, fmt.Errorf("unable to record database stats: %w", err)
}