Extend tracing and metrics
Tracing: OTLP gRPC/HTTP exporters with TLS and headers, parent-based sampling, W3C TraceContext/Baggage propagation, richer resource attributes, no-export mode without an endpoint, Disabled flag, and Trace/RecordError/TraceID helpers. Metrics: idempotent registration, Sub, GaugeFunc, CounterFunc, RegisterDBStats, OpenMetrics handler with trace exemplars. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2c83b28342
commit
022db31878
7 files changed
+572
-55
No files matched your search
+186
@@ -2,13 +2,18 @@ package obsx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func setupTestTracer(t *testing.T) *tracetest.InMemoryExporter {
|
||||
@@ -125,3 +130,184 @@ func TestStartSpan_CreatesSpan(t *testing.T) {
|
||||
t.Errorf("expected span name 'my-operation', got %q", spans[0].Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewExporter_Selection(t *testing.T) {
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "")
|
||||
ctx := context.Background()
|
||||
|
||||
exp, err := newExporter(ctx, TracerConfig{Protocol: ProtocolGRPC})
|
||||
if err != nil || exp != nil {
|
||||
t.Errorf("no endpoint: exporter = %v, err = %v; want nil, nil", exp, err)
|
||||
}
|
||||
|
||||
for _, cfg := range []TracerConfig{
|
||||
{Protocol: ProtocolGRPC, Endpoint: "localhost:4317"},
|
||||
{Protocol: ProtocolGRPC, Endpoint: "https://collector:4317", Headers: map[string]string{"x-token": "t"}},
|
||||
{Protocol: ProtocolHTTP, Endpoint: "localhost:4318"},
|
||||
{Protocol: "http/protobuf", Endpoint: "http://localhost:4318/v1/traces"},
|
||||
} {
|
||||
exp, err := newExporter(ctx, cfg)
|
||||
if err != nil || exp == nil {
|
||||
t.Errorf("%+v: exporter = %v, err = %v", cfg, exp, err)
|
||||
continue
|
||||
}
|
||||
_ = exp.Shutdown(ctx)
|
||||
}
|
||||
|
||||
if _, err := newExporter(ctx, TracerConfig{Protocol: "thrift", Endpoint: "x:1"}); err == nil {
|
||||
t.Error("expected error for unsupported protocol")
|
||||
}
|
||||
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317")
|
||||
exp, err = newExporter(ctx, TracerConfig{Protocol: ProtocolGRPC})
|
||||
if err != nil || exp == nil {
|
||||
t.Errorf("env endpoint: exporter = %v, err = %v", exp, err)
|
||||
} else {
|
||||
_ = exp.Shutdown(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTracerProvider_NoExporterStillTraces(t *testing.T) {
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "")
|
||||
tp, shutdown, err := newTracerProvider(context.Background(), TracerConfig{ServiceName: "local"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer shutdown(context.Background())
|
||||
|
||||
ctx, span := tp.Tracer("t").Start(context.Background(), "op")
|
||||
defer span.End()
|
||||
if TraceID(ctx) == "" {
|
||||
t.Error("spans must have trace IDs even without an exporter (log correlation)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTracerProvider_Disabled(t *testing.T) {
|
||||
tp, shutdown, err := newTracerProvider(context.Background(), TracerConfig{Disabled: true, Endpoint: "localhost:4317"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := shutdown(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
ctx, span := tp.Tracer("t").Start(context.Background(), "op")
|
||||
span.End()
|
||||
if TraceID(ctx) != "" {
|
||||
t.Error("disabled tracing must not create spans")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTracerProvider_ParentBasedSampling(t *testing.T) {
|
||||
exp := tracetest.NewInMemoryExporter()
|
||||
tp, shutdown, err := newTracerProvider(context.Background(), TracerConfig{Sampler: 0.000001, Exporter: exp})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer shutdown(context.Background())
|
||||
|
||||
// A sampled parent from an upstream service must be honored.
|
||||
parent := trace.NewSpanContext(trace.SpanContextConfig{
|
||||
TraceID: trace.TraceID{1},
|
||||
SpanID: trace.SpanID{1},
|
||||
TraceFlags: trace.FlagsSampled,
|
||||
Remote: true,
|
||||
})
|
||||
_, span := tp.Tracer("t").Start(trace.ContextWithRemoteSpanContext(context.Background(), parent), "child")
|
||||
if !span.SpanContext().IsSampled() {
|
||||
t.Error("child of a sampled remote parent must be sampled")
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
|
||||
func TestNewResource_Attributes(t *testing.T) {
|
||||
res, err := newResource(context.Background(), TracerConfig{
|
||||
ServiceName: "svc",
|
||||
ServiceVersion: "v1",
|
||||
Environment: "prod",
|
||||
Attributes: []attribute.KeyValue{attribute.String("team", "payments")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[string]string{}
|
||||
for _, kv := range res.Attributes() {
|
||||
got[string(kv.Key)] = kv.Value.Emit()
|
||||
}
|
||||
for k, v := range map[string]string{
|
||||
"service.name": "svc",
|
||||
"service.version": "v1",
|
||||
"deployment.environment": "prod",
|
||||
"team": "payments",
|
||||
} {
|
||||
if got[k] != v {
|
||||
t.Errorf("resource %s = %q, want %q", k, got[k], v)
|
||||
}
|
||||
}
|
||||
if got["service.instance.id"] == "" {
|
||||
t.Error("service.instance.id not set")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrace_RecordsError(t *testing.T) {
|
||||
prev := otel.GetTracerProvider()
|
||||
t.Cleanup(func() { otel.SetTracerProvider(prev) })
|
||||
exp := setupTestTracer(t)
|
||||
|
||||
want := errors.New("failed")
|
||||
var inner context.Context
|
||||
err := Trace(context.Background(), "work", func(ctx context.Context) error {
|
||||
inner = ctx
|
||||
return want
|
||||
})
|
||||
if !errors.Is(err, want) {
|
||||
t.Fatalf("Trace returned %v", err)
|
||||
}
|
||||
if TraceID(inner) == "" {
|
||||
t.Error("fn context carries no span")
|
||||
}
|
||||
|
||||
spans := exp.GetSpans()
|
||||
if len(spans) != 1 || spans[0].Status.Code != codes.Error || len(spans[0].Events) != 1 {
|
||||
t.Errorf("unexpected spans: %+v", spans)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordError(t *testing.T) {
|
||||
prev := otel.GetTracerProvider()
|
||||
t.Cleanup(func() { otel.SetTracerProvider(prev) })
|
||||
exp := setupTestTracer(t)
|
||||
|
||||
ctx, span := StartSpan(context.Background(), "op")
|
||||
RecordError(ctx, nil)
|
||||
RecordError(ctx, errors.New("bad"))
|
||||
span.End()
|
||||
|
||||
s := exp.GetSpans()[0]
|
||||
if s.Status.Code != codes.Error || len(s.Events) != 1 {
|
||||
t.Errorf("unexpected span: status=%v events=%d", s.Status.Code, len(s.Events))
|
||||
}
|
||||
if TraceID(context.Background()) != "" {
|
||||
t.Error("TraceID without span must be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupTracer_SetsPropagator(t *testing.T) {
|
||||
prevTP, prevProp := otel.GetTracerProvider(), otel.GetTextMapPropagator()
|
||||
t.Cleanup(func() {
|
||||
otel.SetTracerProvider(prevTP)
|
||||
otel.SetTextMapPropagator(prevProp)
|
||||
})
|
||||
|
||||
shutdown, err := SetupTracer(context.Background(), TracerConfig{Exporter: tracetest.NewInMemoryExporter()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer shutdown(context.Background())
|
||||
|
||||
fields := otel.GetTextMapPropagator().Fields()
|
||||
if !slices.Contains(fields, "traceparent") || !slices.Contains(fields, "baggage") {
|
||||
t.Errorf("propagator fields = %v, want traceparent and baggage", fields)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user