Files
tenant-registry/internal/telemetry/pgx.go
T
Sharang ParnerkarandClaude Opus 5.5 65ad1b52f6
ci / shared (pull_request) Failing after 12s
ci / test (pull_request) Failing after 15m24s
ci / image (pull_request) Skipped
feat(telemetry): traces to SigNoz for requests, outbound calls and SQL
internal/telemetry: OTLP/HTTP tracer provider from the OTEL_* env
(already set on stage and prod; unset = off), W3C propagation, one server
span per request named after the ServeMux pattern, client spans on the
default transport (Keycloak, ERP, LiteLLM, OIDC) and a pgx QueryTracer.
Client and DB spans only inside a request, so the background loops add
no traces. No raw paths, query strings, bodies, SQL parameters or client
addresses in spans; outbound spans carry the host only.

slog lines logged with a request context get trace_id/span_id; the
access log names the route instead of the raw path (slugs are names).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KYcAAeTw22GE9QPzDM8yc4
2026-10-28 22:24:34 +01:00

62 lines
1.6 KiB
Go

package telemetry
import (
"context"
"strings"
"github.com/jackc/pgx/v5"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
// maxStatement caps db.query.text; the statements are ours and use $n
// placeholders, parameters are never recorded.
const maxStatement = 2000
// QueryTracer is a pgx.QueryTracer: one span per query inside a request.
type QueryTracer struct{}
type spanKey struct{}
func (QueryTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
if !hasParent(ctx) {
return ctx
}
op := operation(data.SQL)
ctx, span := tracer().Start(ctx, "db "+op, trace.WithSpanKind(trace.SpanKindClient), trace.WithAttributes(
attribute.String("db.system.name", "postgresql"),
attribute.String("db.operation.name", op),
attribute.String("db.query.text", truncate(strings.TrimSpace(data.SQL), maxStatement)),
))
// Marked so TraceQueryEnd never ends a span it did not start (the parent).
return context.WithValue(ctx, spanKey{}, span)
}
func (QueryTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
span, ok := ctx.Value(spanKey{}).(trace.Span)
if !ok {
return
}
if data.Err != nil && data.Err != pgx.ErrNoRows {
span.SetStatus(codes.Error, "query failed")
}
span.End()
}
// operation is the statement's first keyword (SELECT, INSERT, WITH, …).
func operation(sql string) string {
f := strings.Fields(sql)
if len(f) == 0 {
return "QUERY"
}
return strings.ToUpper(f[0])
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n]
}