The service map draws database nodes from the pre-1.26 db.system key (dependency_graph_minutes_db_calls_mv_v2); the spans set only db.system.name, so the registry's Postgres never appeared on the map. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KYcAAeTw22GE9QPzDM8yc4
65 lines
1.8 KiB
Go
65 lines
1.8 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"),
|
|
// The pre-1.26 key as well: SigNoz's service map draws database nodes
|
|
// from db.system (dependency_graph_minutes_db_calls_mv_v2).
|
|
attribute.String("db.system", "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]
|
|
}
|