package telemetry import ( "context" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "github.com/redis/go-redis/v9" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" "net" "strings" ) // Queries are named by operation only. SQL text/args never enter telemetry. type DBTracer struct{} func (DBTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context { if !trace.SpanContextFromContext(ctx).IsValid() { return ctx } op := "OTHER" f := strings.Fields(d.SQL) if len(f) > 0 { switch strings.ToUpper(f[0]) { case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK", "CREATE", "ALTER": op = strings.ToUpper(f[0]) } } c, _ := Span(ctx, "db."+strings.ToLower(op), trace.SpanKindClient, attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", op)) return c } func (DBTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) { if trace.SpanContextFromContext(ctx).IsValid() { Result(trace.SpanFromContext(ctx), d.Err) } } func (DBTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context { Waiting.Add(1) if trace.SpanContextFromContext(ctx).IsValid() { c, _ := Span(ctx, "db.pool.acquire", trace.SpanKindClient, attribute.String("db.system.name", "postgresql")) return c } return ctx } func (DBTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) { Waiting.Add(-1) if trace.SpanContextFromContext(ctx).IsValid() { Result(trace.SpanFromContext(ctx), data.Err) } } type RedisHook struct{} func (RedisHook) DialHook(next redis.DialHook) redis.DialHook { return func(ctx context.Context, network, addr string) (net.Conn, error) { return next(ctx, network, addr) } } func (RedisHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook { return func(ctx context.Context, cmd redis.Cmder) error { if !trace.SpanContextFromContext(ctx).IsValid() { return next(ctx, cmd) } c, s := Span(ctx, "redis."+cmd.Name(), trace.SpanKindClient, attribute.String("db.system.name", "redis"), attribute.String("db.operation.name", cmd.Name())) err := next(c, cmd) if err == redis.Nil { s.End() } else { Result(s, err) } return err } } func (RedisHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { return next }