Add HTTPMiddleware, HTTPTransport and LogHandler; extend TracerConfig with Insecure, Headers and Attributes; install W3C propagators; parent-based sampling; end-to-end OTLP export tests; update dependencies (Go 1.26). Breaking since v0.2.0: the OTLP connection uses TLS unless Insecure is set. Co-Authored-By: Claude <noreply@anthropic.com>
137 lines
4.2 KiB
Go
137 lines
4.2 KiB
Go
package obsx
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/propagation"
|
|
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
|
)
|
|
|
|
const parentTrace = "4bf92f3577b34da6a3ce929d0e0e4736"
|
|
|
|
func setupPropagation(t *testing.T) *tracetest.InMemoryExporter {
|
|
t.Helper()
|
|
prevTP, prevProp := otel.GetTracerProvider(), otel.GetTextMapPropagator()
|
|
t.Cleanup(func() {
|
|
otel.SetTracerProvider(prevTP)
|
|
otel.SetTextMapPropagator(prevProp)
|
|
})
|
|
otel.SetTextMapPropagator(propagation.TraceContext{})
|
|
return setupTestTracer(t)
|
|
}
|
|
|
|
func TestHTTPMiddleware(t *testing.T) {
|
|
exp := setupPropagation(t)
|
|
m := NewMetrics(MetricsConfig{Namespace: "test"})
|
|
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {})
|
|
mux.HandleFunc("GET /fail", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
})
|
|
mux.HandleFunc("GET /panic", func(w http.ResponseWriter, r *http.Request) { panic("boom") })
|
|
h := HTTPMiddleware(m)(mux)
|
|
|
|
req := httptest.NewRequest("GET", "/users/42", nil)
|
|
req.Header.Set("traceparent", "00-"+parentTrace+"-00f067aa0ba902b7-01")
|
|
h.ServeHTTP(httptest.NewRecorder(), req)
|
|
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/fail", nil))
|
|
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("WEIRD", "/nope", nil))
|
|
func() {
|
|
defer func() {
|
|
if recover() == nil {
|
|
t.Error("expected the handler panic to propagate")
|
|
}
|
|
}()
|
|
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/panic", nil))
|
|
}()
|
|
|
|
spans := exp.GetSpans()
|
|
if len(spans) != 4 {
|
|
t.Fatalf("expected 4 spans, got %d", len(spans))
|
|
}
|
|
if spans[0].Name != "GET /users/{id}" {
|
|
t.Errorf("span name = %q", spans[0].Name)
|
|
}
|
|
if got := spans[0].SpanContext.TraceID().String(); got != parentTrace {
|
|
t.Errorf("trace not continued from header: trace id %s", got)
|
|
}
|
|
|
|
body := scrape(t, m)
|
|
for _, want := range []string{
|
|
`test_http_requests_total{method="GET",route="GET /users/{id}",status="200"} 1`,
|
|
`test_http_requests_total{method="GET",route="GET /fail",status="500"} 1`,
|
|
`test_http_requests_total{method="GET",route="GET /panic",status="500"} 1`,
|
|
`test_http_requests_total{method="OTHER",route="unmatched",status="404"} 1`,
|
|
`test_http_request_duration_seconds_count{method="GET",route="GET /users/{id}"} 1`,
|
|
} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("missing %q in:\n%s", want, body)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestHTTPMiddleware_NilMetrics(t *testing.T) {
|
|
w := httptest.NewRecorder()
|
|
HTTPMiddleware(nil)(http.NotFoundHandler()).ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
|
|
if w.Code != http.StatusNotFound {
|
|
t.Errorf("status = %d", w.Code)
|
|
}
|
|
}
|
|
|
|
func TestHTTPTransport_PropagatesTrace(t *testing.T) {
|
|
exp := setupPropagation(t)
|
|
|
|
var got string
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
got = r.Header.Get("traceparent")
|
|
}))
|
|
defer srv.Close()
|
|
|
|
ctx, parent := StartSpan(context.Background(), "parent")
|
|
req, _ := http.NewRequestWithContext(ctx, "GET", srv.URL, nil)
|
|
resp, err := (&http.Client{Transport: HTTPTransport(nil)}).Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
resp.Body.Close()
|
|
parent.End()
|
|
|
|
if !strings.Contains(got, parent.SpanContext().TraceID().String()) {
|
|
t.Errorf("traceparent %q does not carry trace %s", got, parent.SpanContext().TraceID())
|
|
}
|
|
if req.Header.Get("traceparent") != "" {
|
|
t.Error("caller's request was modified")
|
|
}
|
|
if n := len(exp.GetSpans()); n != 2 {
|
|
t.Errorf("expected parent + client span, got %d", n)
|
|
}
|
|
}
|
|
|
|
func TestLogHandler(t *testing.T) {
|
|
setupPropagation(t)
|
|
var buf bytes.Buffer
|
|
log := slog.New(LogHandler(slog.NewJSONHandler(&buf, nil))).With("k", "v")
|
|
|
|
ctx, span := StartSpan(context.Background(), "op")
|
|
defer span.End()
|
|
log.InfoContext(ctx, "hello")
|
|
log.Info("no span")
|
|
|
|
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
|
|
if !strings.Contains(lines[0], `"trace_id":"`+span.SpanContext().TraceID().String()+`"`) ||
|
|
!strings.Contains(lines[0], `"span_id":"`+span.SpanContext().SpanID().String()+`"`) {
|
|
t.Errorf("trace ids missing: %s", lines[0])
|
|
}
|
|
if strings.Contains(lines[1], "trace_id") {
|
|
t.Errorf("unexpected trace id: %s", lines[1])
|
|
}
|
|
}
|