Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,17 @@ if err := otelpgx.RecordStats(conn); err != nil {
}
```

See [options.go](options.go) for the full list of options.
See [options.go](options.go) for the full list of options.

### Filtering span errors

Use `WithSpanErrorFilter` to omit expected errors from spans while keeping
other errors visible. This example omits client cancellations, including wrapped errors.

```go
cfg.ConnConfig.Tracer = otelpgx.NewTracer(
otelpgx.WithSpanErrorFilter(func(err error) bool {
return !errors.Is(err, context.Canceled)
}),
)
```
12 changes: 12 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ func WithTracerAttributes(attrs ...attribute.KeyValue) Option {
})
}

// WithSpanErrorFilter controls which errors are recorded on spans.
// Return true to record the error and set the span status to Error.
// Return false to omit the exception event, error status, and SQLSTATE attribute.
// The filter may be called concurrently and only receives non-nil errors other
// than sql.ErrNoRows and errors wrapping it. A nil filter uses the default
// behavior. Database operation metrics use their standard error classification.
func WithSpanErrorFilter(filter func(error) bool) Option {
return optionFunc(func(cfg *tracerConfig) {
cfg.spanErrorFilter = filter
})
}

// WithMeterAttributes specifies additional attributes to be added to metrics.
func WithMeterAttributes(attrs ...attribute.KeyValue) Option {
return optionFunc(func(cfg *tracerConfig) {
Expand Down
41 changes: 23 additions & 18 deletions tracer.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ type Tracer struct {

fullQuerySpanName bool
spanNameCtxFunc SpanNameCtxFunc
spanErrorFilter func(error) bool
prefixQuerySpanName bool
logSQLStatement bool
logConnectionDetails bool
Expand All @@ -99,6 +100,7 @@ type tracerConfig struct {

fullQuerySpanName bool
spanNameCtxFunc SpanNameCtxFunc
spanErrorFilter func(error) bool
prefixQuerySpanName bool
logSQLStatement bool
logConnectionDetails bool
Expand Down Expand Up @@ -151,6 +153,7 @@ func NewTracer(opts ...Option) *Tracer {
meterAttrs: cfg.meterAttrs,
fullQuerySpanName: cfg.fullQuerySpanName,
spanNameCtxFunc: cfg.spanNameCtxFunc,
spanErrorFilter: cfg.spanErrorFilter,
prefixQuerySpanName: cfg.prefixQuerySpanName,
logSQLStatement: cfg.logSQLStatement,
logConnectionDetails: cfg.logConnectionDetails,
Expand Down Expand Up @@ -206,18 +209,20 @@ func (t *Tracer) createAttributeSets() {
}
}

// recordSpanError handles all error handling to be applied on the provided span.
// The provided error must be non-nil and not a sql.ErrNoRows error.
// Otherwise, recordSpanError will be a no-op.
func recordSpanError(span trace.Span, err error) {
if err != nil && !errors.Is(err, sql.ErrNoRows) {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
func (t *Tracer) recordSpanError(span trace.Span, err error) {
if err == nil || errors.Is(err, sql.ErrNoRows) || !span.IsRecording() {
return
}
if t.spanErrorFilter != nil && !t.spanErrorFilter(err) {
return
}

var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
span.SetAttributes(SQLStateKey.String(pgErr.Code))
}
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())

var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
span.SetAttributes(SQLStateKey.String(pgErr.Code))
}
}

Expand Down Expand Up @@ -362,7 +367,7 @@ func (t *Tracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQ
return
}

recordSpanError(span, data.Err)
t.recordSpanError(span, data.Err)

if data.Err == nil {
span.SetAttributes(RowsAffectedKey.Int64(data.CommandTag.RowsAffected()))
Expand Down Expand Up @@ -421,7 +426,7 @@ func (t *Tracer) TraceCopyFromEnd(ctx context.Context, _ *pgx.Conn, data pgx.Tra
span.SetAttributes(RowsAffectedKey.Int64(data.CommandTag.RowsAffected()))
}

recordSpanError(span, data.Err)
t.recordSpanError(span, data.Err)
span.End()
}

Expand Down Expand Up @@ -516,7 +521,7 @@ func (t *Tracer) TraceBatchQuery(ctx context.Context, conn *pgx.Conn, data pgx.T
spanName := t.spanName(data.SQL, operationName, "batch query ")

_, span := t.tracer.Start(ctx, spanName, opts...)
recordSpanError(span, data.Err)
t.recordSpanError(span, data.Err)

span.End()
}
Expand All @@ -535,7 +540,7 @@ func (t *Tracer) TraceBatchEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceB
return
}

recordSpanError(span, data.Err)
t.recordSpanError(span, data.Err)
span.End()
}

Expand Down Expand Up @@ -584,7 +589,7 @@ func (t *Tracer) TraceConnectEnd(ctx context.Context, data pgx.TraceConnectEndDa
return
}

recordSpanError(span, data.Err)
t.recordSpanError(span, data.Err)
span.End()
}

Expand Down Expand Up @@ -652,7 +657,7 @@ func (t *Tracer) TracePrepareEnd(ctx context.Context, _ *pgx.Conn, data pgx.Trac
return
}

recordSpanError(span, data.Err)
t.recordSpanError(span, data.Err)
span.End()
}

Expand Down Expand Up @@ -710,7 +715,7 @@ func (t *Tracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxp
return
}

recordSpanError(span, data.Err)
t.recordSpanError(span, data.Err)
span.End()
}

Expand Down
102 changes: 102 additions & 0 deletions tracer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ import (
"testing"

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgproto3"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/metric/metricdata"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
Expand Down Expand Up @@ -565,6 +567,106 @@ func TestTracer_spanName(t *testing.T) {
}
}

func TestTracer_spanErrorFilter(t *testing.T) {
ignoreCancellation := WithSpanErrorFilter(func(err error) bool {
return !errors.Is(err, context.Canceled)
})
dbError := &pgconn.PgError{Code: "28P01", Message: "invalid password"}
tests := []struct {
name string
err error
opts []Option
wantSpanError bool
wantSQLState string
wantErrorCount int64
}{
{
name: "cancellation is recorded by default",
err: context.Canceled,
wantSpanError: true,
wantErrorCount: 1,
},
{
name: "wrapped cancellation is filtered from the span only",
err: fmt.Errorf("query: %w", context.Canceled),
opts: []Option{ignoreCancellation},
wantErrorCount: 1,
},
{
name: "database error still records the SQLSTATE",
err: fmt.Errorf("query: %w", dbError),
opts: []Option{ignoreCancellation},
wantSpanError: true,
wantSQLState: "28P01",
wantErrorCount: 1,
},
{
name: "wrapped no rows remains exempt",
err: fmt.Errorf("query: %w", pgx.ErrNoRows),
opts: []Option{WithSpanErrorFilter(func(error) bool { return true })},
},
{
name: "success remains exempt",
opts: []Option{WithSpanErrorFilter(func(error) bool { return true })},
},
{
name: "nil filter restores default recording",
err: context.Canceled,
opts: []Option{ignoreCancellation, WithSpanErrorFilter(nil)},
wantSpanError: true,
wantErrorCount: 1,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := tracetest.NewSpanRecorder()
tp := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder))
reader := sdkmetric.NewManualReader()
mp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
t.Cleanup(func() { require.NoError(t, tp.Shutdown(context.Background())) })
t.Cleanup(func() { require.NoError(t, mp.Shutdown(context.Background())) })
opts := append([]Option{WithTracerProvider(tp), WithMeterProvider(mp)}, tt.opts...)
tracer := NewTracer(opts...)

ctx := context.Background()
parentCtx, parentSpan := tp.Tracer("test").Start(ctx, "parent")
queryCtx := tracer.TraceQueryStart(parentCtx, nil, pgx.TraceQueryStartData{SQL: "SELECT 1"})
tracer.TraceQueryEnd(queryCtx, nil, pgx.TraceQueryEndData{Err: tt.err})
parentSpan.End()

spans := recorder.Ended()
require.Len(t, spans, 2)
span := spans[0]
if tt.wantSpanError {
assert.Equal(t, sdktrace.Status{Code: codes.Error, Description: tt.err.Error()}, span.Status())
require.Len(t, span.Events(), 1)
assert.Equal(t, "exception", span.Events()[0].Name)
} else {
assert.Equal(t, codes.Unset, span.Status().Code)
assert.Empty(t, span.Events())
}
attrs := attribute.NewSet(span.Attributes()...)
state, ok := attrs.Value(SQLStateKey)
assert.Equal(t, tt.wantSQLState != "", ok)
assert.Equal(t, tt.wantSQLState, state.AsString())

var rm metricdata.ResourceMetrics
require.NoError(t, reader.Collect(ctx, &rm))
require.Len(t, rm.ScopeMetrics, 1)
var errorCount int64
for _, m := range rm.ScopeMetrics[0].Metrics {
if m.Name == string(DBClientOperationErrorsKey) {
points := m.Data.(metricdata.Sum[int64]).DataPoints
require.Len(t, points, 1)
errorCount = points[0].Value
}
}
assert.Equal(t, tt.wantErrorCount, errorCount)
})
}
}

func TestTracer_metricOperationName(t *testing.T) {
conn := newMockConn(t, "fakehost", 5432, "fakeuser", "fakedb")
boom := errors.New("boom")
Expand Down