From 2c83b28342518fd8a753f88bebfcb51e4d85b4a7 Mon Sep 17 00:00:00 2001 From: Aleksey Shakhmatov Date: Tue, 10 Nov 2026 20:20:09 +0300 Subject: [PATCH] Release v1.0.0: HTTP instrumentation, slog correlation, TLS by default 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 --- AGENTS.md | 13 +++-- CHANGELOG.md | 19 +++++++ CLAUDE.md | 12 ++-- README.md | 61 +++++++++++++++++--- config.go | 1 - doc.go | 21 +++++-- example_test.go | 45 +++++++++++++++ export_test.go | 98 ++++++++++++++++++++++++++++++++ go.mod | 48 ++++++++-------- go.sum | 116 ++++++++++++++++++++------------------ http.go | 147 ++++++++++++++++++++++++++++++++++++++++++++++++ http_test.go | 136 ++++++++++++++++++++++++++++++++++++++++++++ log.go | 33 +++++++++++ tracer.go | 61 ++++++++++++++------ tracer_test.go | 3 + 15 files changed, 695 insertions(+), 119 deletions(-) create mode 100644 CHANGELOG.md delete mode 100644 config.go create mode 100644 example_test.go create mode 100644 export_test.go create mode 100644 http.go create mode 100644 http_test.go create mode 100644 log.go diff --git a/AGENTS.md b/AGENTS.md index db06997..bee6980 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,16 +4,17 @@ Universal guide for AI coding agents working with this codebase. ## Overview -`git.codelab.vc/pkg/obsx` is a Go observability library providing Prometheus metrics and OpenTelemetry tracing setup with consistent defaults and isolated registries. +`git.codelab.vc/pkg/obsx` is a Go observability library providing Prometheus metrics, OpenTelemetry tracing, trace-correlated slog logging and HTTP instrumentation with consistent defaults and isolated registries. The public API is stable (v1): do not break it. ## Package map ``` -obsx/ Root — tracing, metrics, config +obsx/ Root — single package ├── doc.go Package documentation ├── tracer.go SetupTracer, StartSpan, TracerConfig ├── metrics.go Metrics factory, NewMetrics, Counter/Histogram/Gauge, Handler -└── config.go (empty — configs are co-located with their components) +├── http.go HTTPMiddleware (server), HTTPTransport (client) +└── log.go LogHandler (slog trace correlation) ``` ## Architecture @@ -65,8 +66,10 @@ obsx/ Root — tracing, metrics, config - **SetupTracer sets the global provider**: calling it multiple times overwrites the previous provider; the old provider is not shut down automatically - **Isolated registry**: `NewMetrics` creates its own `prometheus.Registry`, not the global default. Metrics registered here will not appear in `promhttp.Handler()` — use `m.Handler()` instead - **Sampler default**: if `TracerConfig.Sampler` is 0 or negative, it defaults to 1.0 (sample everything), not 0 -- **Insecure gRPC**: `SetupTracer` always uses `otlptracegrpc.WithInsecure()` — no TLS for the OTLP endpoint -- **StartSpan tracer name**: uses the hardcoded tracer name `"obsx"` — all spans created via this helper share the same instrumentation scope +- **TLS by default**: the OTLP connection is plaintext only with `TracerConfig.Insecure: true` +- **Tracer name**: `StartSpan` and the HTTP instrumentation share the instrumentation scope `git.codelab.vc/pkg/obsx` +- **HTTPMiddleware registers metrics**: calling it twice with the same `Metrics` panics (duplicate registration); the route label comes from `Request.Pattern`, so it must wrap the `http.ServeMux` directly +- **LogHandler needs the context**: only `slog.*Context` calls get `trace_id` / `span_id` ## Commands diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..be82300 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,19 @@ +# Changelog + +## v1.0.0 + +The API is stable from this release on (semantic versioning). + +### Added + +- `HTTPMiddleware` — server spans with trace continuation plus `http_requests_total` and `http_request_duration_seconds` metrics. +- `HTTPTransport` — client spans and trace context propagation for outgoing requests. +- `LogHandler` — `slog.Handler` wrapper adding `trace_id` / `span_id` to records. +- `TracerConfig.Insecure`, `TracerConfig.Headers`, `TracerConfig.Attributes`. +- `SetupTracer` installs W3C TraceContext + Baggage propagators and honours `OTEL_EXPORTER_OTLP_*` / `OTEL_RESOURCE_ATTRIBUTES`. + +### Changed (breaking since v0.2.0) + +- **OTLP connection uses TLS by default.** Set `TracerConfig.Insecure: true` for plaintext collectors — previously the connection was always insecure. +- Sampling is parent-based: `Sampler` applies to root traces, child spans follow the parent's decision. +- `StartSpan` instrumentation scope is `git.codelab.vc/pkg/obsx` (was `obsx`). diff --git a/CLAUDE.md b/CLAUDE.md index f1f6ef2..c1849a9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,14 +12,17 @@ go vet ./... # static analysis ## Architecture -- **Module**: `git.codelab.vc/pkg/obsx`, Go 1.25.7, depends on OpenTelemetry and Prometheus client_golang +- **Module**: `git.codelab.vc/pkg/obsx`, Go 1.26, depends on OpenTelemetry and Prometheus client_golang - **Single package** `obsx` ### Core patterns -- **SetupTracer** — creates OTLP gRPC exporter, builds `sdktrace.TracerProvider` with batcher and ratio sampler, sets it as global `otel.TracerProvider` -- **StartSpan** — convenience function using `otel.Tracer("obsx")` to start spans via the global provider -- **TracerConfig** — service name, version, OTLP endpoint, sampling ratio; `defaults()` sets `Sampler` to 1.0 if unset +- **SetupTracer** — creates OTLP gRPC exporter (TLS unless `Insecure`), builds `sdktrace.TracerProvider` with batcher and parent-based ratio sampler, sets it and W3C propagators as OpenTelemetry globals +- **StartSpan** — convenience function starting spans via the global provider +- **TracerConfig** — service name, version, OTLP endpoint, insecure, headers, sampling ratio, resource attributes; `defaults()` sets `Sampler` to 1.0 if unset +- **HTTPMiddleware** — server span + `http_requests_total` / `http_request_duration_seconds` per request; route label from `Request.Pattern` +- **HTTPTransport** — `http.RoundTripper` with client spans and trace context injection +- **LogHandler** — `slog.Handler` wrapper adding `trace_id` / `span_id` - **Metrics** — factory that creates Prometheus `CounterVec`, `HistogramVec`, `GaugeVec` with consistent namespace/subsystem - **NewMetrics** — creates an isolated `prometheus.Registry` pre-loaded with process and Go collectors - **Handler()** — returns `promhttp.HandlerFor` using the isolated registry @@ -36,6 +39,7 @@ go vet ./... # static analysis - Isolated Prometheus registry — not the global default, avoids conflicts in tests and multi-tenant setups - `nil` buckets in `Histogram()` defaults to `prometheus.DefBuckets` - No functional options — direct struct configuration only +- Public API is stable since v1.0.0 — no breaking changes; record changes in `CHANGELOG.md` ## See also diff --git a/README.md b/README.md index a671080..5251ddc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # obsx -Observability library for Go providing metrics (Prometheus) and tracing (OpenTelemetry) setup with consistent defaults. Creates a Prometheus registry with process/Go collectors, a metrics factory with namespace/subsystem scoping, and an OTLP gRPC tracer provider with configurable sampling. +Observability for Go services in a few lines: tracing (OpenTelemetry, OTLP gRPC), metrics (Prometheus) and trace-correlated logs (`log/slog`), plus HTTP server middleware and a client transport that tie them together. Stable API since v1.0.0 — see [CHANGELOG.md](CHANGELOG.md). ``` go get git.codelab.vc/pkg/obsx @@ -14,7 +14,8 @@ shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{ ServiceName: "my-service", ServiceVersion: "1.0.0", Endpoint: "localhost:4317", - Sampler: 1.0, // sample everything + Insecure: true, // plaintext; TLS is the default + Sampler: 1.0, // sample everything }) if err != nil { log.Fatal(err) @@ -29,32 +30,46 @@ metrics := obsx.NewMetrics(obsx.MetricsConfig{ reqCounter := metrics.Counter("requests_total", "Total HTTP requests", "method", "status") latency := metrics.Histogram("request_duration_seconds", "Request latency", nil, "method") -http.Handle("/metrics", metrics.Handler()) +// Logs with trace_id / span_id +slog.SetDefault(slog.New(obsx.LogHandler(slog.NewJSONHandler(os.Stderr, nil)))) + +// HTTP: server spans + request metrics, traced outgoing calls +mux := http.NewServeMux() +mux.Handle("GET /metrics", metrics.Handler()) +handler := obsx.HTTPMiddleware(metrics)(mux) +client := &http.Client{Transport: obsx.HTTPTransport(nil)} ``` ## Components | Component | What it does | |-----------|-------------| -| `SetupTracer` | Initializes an OpenTelemetry tracer provider with OTLP gRPC exporter, sets it as the global provider. | +| `SetupTracer` | Initializes an OpenTelemetry tracer provider with OTLP gRPC exporter, sets it and W3C propagators as globals. | | `StartSpan` | Convenience wrapper that starts a span using the global tracer provider. | | `Metrics` | Factory for creating Prometheus metrics with consistent namespace/subsystem naming. | -| `TracerConfig` | Configures the tracer: service name, version, OTLP endpoint, sampling ratio. | +| `HTTPMiddleware` | Server middleware: span per request (continues incoming traces) and request count/duration metrics. | +| `HTTPTransport` | `http.RoundTripper` that creates client spans and propagates trace context. | +| `LogHandler` | Wraps any `slog.Handler` to add `trace_id` / `span_id` to records. | +| `TracerConfig` | Configures the tracer: service name, version, OTLP endpoint, TLS, headers, sampling ratio, resource attributes. | | `MetricsConfig` | Configures the metrics factory: namespace and subsystem. | ## Tracing -`SetupTracer` creates an OTLP gRPC exporter, builds a tracer provider with batched span export and ratio-based sampling, and registers it as the global `otel.TracerProvider`. Returns a shutdown function that must be called on application exit. +`SetupTracer` creates an OTLP gRPC exporter, builds a tracer provider with batched span export and parent-based ratio sampling, and registers it — together with W3C TraceContext and Baggage propagators — as the OpenTelemetry globals. Returns a shutdown function that must be called on application exit. ```go shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{ ServiceName: "orders-api", - Endpoint: "jaeger:4317", - Sampler: 0.1, // sample 10% + Endpoint: "otel.example.com:4317", // TLS unless Insecure is set + Headers: map[string]string{"authorization": "Bearer " + token}, + Sampler: 0.1, // sample 10% of root traces + Attributes: []attribute.KeyValue{attribute.String("deployment.environment.name", "prod")}, }) defer shutdown(ctx) ``` +With an empty `Endpoint` the standard `OTEL_EXPORTER_OTLP_*` environment variables apply; `OTEL_RESOURCE_ATTRIBUTES` is honoured too. + Start spans with the convenience helper: ```go @@ -89,6 +104,34 @@ Access the underlying registry directly: registry := m.Registry() ``` +## HTTP + +`HTTPMiddleware` wraps a handler (wrap the `http.ServeMux` itself so the route pattern is known). Per request it starts a server span named after the matched pattern, continuing the trace from incoming headers, and — when given a `*Metrics` — records: + +| Metric | Labels | +|--------|--------| +| `_http_requests_total` | `method`, `route`, `status` | +| `_http_request_duration_seconds` | `method`, `route` | + +```go +handler := obsx.HTTPMiddleware(metrics)(mux) // pass nil for tracing only +``` + +`HTTPTransport` instruments outgoing requests with a client span and injects the trace context: + +```go +client := &http.Client{Transport: obsx.HTTPTransport(nil)} // nil = http.DefaultTransport +``` + +## Logging + +`LogHandler` wraps any `slog.Handler`; records logged with a span-carrying context get `trace_id` and `span_id`: + +```go +slog.SetDefault(slog.New(obsx.LogHandler(slog.NewJSONHandler(os.Stderr, nil)))) +slog.InfoContext(ctx, "order created") +``` + ## Requirements -Go 1.24+, [OpenTelemetry Go](https://opentelemetry.io/docs/languages/go/), [Prometheus client_golang](https://github.com/prometheus/client_golang). +Go 1.26+, [OpenTelemetry Go](https://opentelemetry.io/docs/languages/go/), [Prometheus client_golang](https://github.com/prometheus/client_golang). diff --git a/config.go b/config.go deleted file mode 100644 index bdcdf70..0000000 --- a/config.go +++ /dev/null @@ -1 +0,0 @@ -package obsx diff --git a/doc.go b/doc.go index 2beaa4b..4c57fd2 100644 --- a/doc.go +++ b/doc.go @@ -1,17 +1,28 @@ -// Package obsx provides observability setup for the platform: metrics (Prometheus) -// and tracing (OpenTelemetry). +// Package obsx wires observability into a Go service: tracing (OpenTelemetry), +// metrics (Prometheus) and trace-correlated logs (log/slog). // // # Quick Start // -// // Tracing +// // Tracing: global tracer provider + W3C propagation // shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{ // ServiceName: "my-service", // Endpoint: "localhost:4317", +// Insecure: true, // }) // defer shutdown(ctx) // +// // Logs carry trace_id / span_id +// slog.SetDefault(slog.New(obsx.LogHandler(slog.NewJSONHandler(os.Stderr, nil)))) +// // // Metrics // metrics := obsx.NewMetrics(obsx.MetricsConfig{Namespace: "myapp"}) -// reqCounter := metrics.Counter("requests_total", "Total requests", "method", "status") -// http.Handle("/metrics", metrics.Handler()) +// mux.Handle("GET /metrics", metrics.Handler()) +// +// // HTTP server spans + request metrics, and traced outgoing calls +// handler := obsx.HTTPMiddleware(metrics)(mux) +// client := &http.Client{Transport: obsx.HTTPTransport(nil)} +// +// # Stability +// +// The package follows semantic versioning; the v1 API is stable. package obsx diff --git a/example_test.go b/example_test.go new file mode 100644 index 0000000..b9e9a52 --- /dev/null +++ b/example_test.go @@ -0,0 +1,45 @@ +package obsx_test + +import ( + "context" + "log" + "log/slog" + "net/http" + "os" + + "git.codelab.vc/pkg/obsx" +) + +// A service with traces, metrics and trace-correlated logs. +func Example() { + ctx := context.Background() + + shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{ + ServiceName: "orders-api", + Endpoint: "localhost:4317", + Insecure: true, + }) + if err != nil { + log.Fatal(err) + } + defer shutdown(ctx) + + slog.SetDefault(slog.New(obsx.LogHandler(slog.NewJSONHandler(os.Stderr, nil)))) + + metrics := obsx.NewMetrics(obsx.MetricsConfig{Namespace: "orders"}) + orders := metrics.Counter("created_total", "Orders created.", "kind") + + mux := http.NewServeMux() + mux.Handle("GET /metrics", metrics.Handler()) + mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) { + ctx, span := obsx.StartSpan(r.Context(), "create-order") + defer span.End() + orders.WithLabelValues("web").Inc() + slog.InfoContext(ctx, "order created") // carries trace_id and span_id + }) + + // Outgoing calls made with this client continue the current trace. + _ = &http.Client{Transport: obsx.HTTPTransport(nil)} + + _ = http.ListenAndServe(":8080", obsx.HTTPMiddleware(metrics)(mux)) +} diff --git a/export_test.go b/export_test.go new file mode 100644 index 0000000..98e0dfb --- /dev/null +++ b/export_test.go @@ -0,0 +1,98 @@ +package obsx + +import ( + "context" + "encoding/pem" + "net" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "go.opentelemetry.io/otel" + coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" +) + +type collector struct { + coltracepb.UnimplementedTraceServiceServer + got chan *coltracepb.ExportTraceServiceRequest +} + +func (c *collector) Export(_ context.Context, r *coltracepb.ExportTraceServiceRequest) (*coltracepb.ExportTraceServiceResponse, error) { + c.got <- r + return &coltracepb.ExportTraceServiceResponse{}, nil +} + +// End to end: spans reach a real OTLP gRPC collector, over plaintext and TLS. +func TestSetupTracer_Exports(t *testing.T) { + for _, insecure := range []bool{true, false} { + name := "tls" + if insecure { + name = "insecure" + } + t.Run(name, func(t *testing.T) { + prev := otel.GetTracerProvider() + t.Cleanup(func() { otel.SetTracerProvider(prev) }) + + var opts []grpc.ServerOption + if !insecure { + // Borrow httptest's self-signed certificate (valid for 127.0.0.1). + ts := httptest.NewTLSServer(nil) + defer ts.Close() + opts = append(opts, grpc.Creds(credentials.NewServerTLSFromCert(&ts.TLS.Certificates[0]))) + ca := filepath.Join(t.TempDir(), "ca.pem") + pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ts.Certificate().Raw}) + if err := os.WriteFile(ca, pemBytes, 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("OTEL_EXPORTER_OTLP_CERTIFICATE", ca) + } + + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + c := &collector{got: make(chan *coltracepb.ExportTraceServiceRequest, 1)} + srv := grpc.NewServer(opts...) + coltracepb.RegisterTraceServiceServer(srv, c) + go srv.Serve(lis) + defer srv.Stop() + + ctx := context.Background() + shutdown, err := SetupTracer(ctx, TracerConfig{ + ServiceName: "export-test", + Endpoint: lis.Addr().String(), + Insecure: insecure, + }) + if err != nil { + t.Fatal(err) + } + _, span := StartSpan(ctx, "exported") + span.End() + if err := shutdown(ctx); err != nil { // flushes + t.Fatalf("shutdown: %v", err) + } + + select { + case r := <-c.got: + rs := r.ResourceSpans[0] + if n := rs.ScopeSpans[0].Spans[0].Name; n != "exported" { + t.Errorf("span name = %q", n) + } + var svc string + for _, a := range rs.Resource.Attributes { + if a.Key == "service.name" { + svc = a.Value.GetStringValue() + } + } + if svc != "export-test" { + t.Errorf("service.name = %q", svc) + } + default: + t.Fatal("collector received no spans") + } + }) + } +} diff --git a/go.mod b/go.mod index 3b0df9b..3c15e54 100644 --- a/go.mod +++ b/go.mod @@ -1,36 +1,38 @@ module git.codelab.vc/pkg/obsx -go 1.25.7 +go 1.26.0 require ( - github.com/prometheus/client_golang v1.22.0 - go.opentelemetry.io/otel v1.35.0 - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0 - go.opentelemetry.io/otel/sdk v1.35.0 - go.opentelemetry.io/otel/trace v1.35.0 + github.com/prometheus/client_golang v1.25.0 + go.opentelemetry.io/otel v1.47.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 + go.opentelemetry.io/otel/sdk v1.47.0 + go.opentelemetry.io/otel/trace v1.47.0 + go.opentelemetry.io/proto/otlp v1.11.1 + google.golang.org/grpc v1.85.0 ) require ( github.com/beorn7/perks v1.0.1 // indirect - github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/prometheus/client_model v0.6.1 // indirect - github.com/prometheus/common v0.62.0 // indirect - github.com/prometheus/procfs v0.15.1 // indirect - go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 // indirect - go.opentelemetry.io/otel/metric v1.35.0 // indirect - go.opentelemetry.io/proto/otlp v1.5.0 // indirect - golang.org/x/net v0.35.0 // indirect - golang.org/x/sys v0.30.0 // indirect - golang.org/x/text v0.22.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a // indirect - google.golang.org/grpc v1.71.0 // indirect - google.golang.org/protobuf v1.36.5 // indirect + github.com/pandatix/go-abnf v0.5.5 // indirect + github.com/prometheus/client_model v0.6.3 // indirect + github.com/prometheus/common v0.73.1 // indirect + github.com/prometheus/procfs v0.23.0 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/otel/metric v1.47.0 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/text v0.44.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect + google.golang.org/protobuf v1.36.12 // indirect ) diff --git a/go.sum b/go.sum index b4c4e7e..4588962 100644 --- a/go.sum +++ b/go.sum @@ -1,14 +1,12 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= -github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= @@ -17,59 +15,65 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1 h1:e9Rjr40Z98/clHv5Yg79Is0NtosR5LXRvdr7o/6NwbA= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1/go.mod h1:tIxuGz/9mpox++sgp9fJjHO0+q1X9/UOWd798aAm22M= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 h1:5T5Ns3kMpWr+z3s5ZA0e7ljVyWNVNxK76sHPAxi5D1k= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0/go.mod h1:oWNYw09cH8wl8fFgC5hKlBLxR4XfKy2KQpP8MJjeCcc= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= -github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= -github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= -github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= -github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= -github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= -github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= -github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= -go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= -go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 h1:1fTNlAIJZGWLP5FVu0fikVry1IsiUnXjf7QFvoNN3Xw= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0/go.mod h1:zjPK58DtkqQFn+YUMbx0M2XV3QgKU0gS9LeGohREyK4= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0 h1:m639+BofXTvcY1q8CGs4ItwQarYtJPOWmVobfM1HpVI= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0/go.mod h1:LjReUci/F4BUyv+y4dwnq3h/26iNOeC3wAIqgvTIZVo= -go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= -go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= -go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY= -go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg= -go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= -go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= -go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= -go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= -go.opentelemetry.io/proto/otlp v1.5.0 h1:xJvq7gMzB31/d406fB8U5CBdyQGw4P399D1aQWU/3i4= -go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWp0eVQ4yIXvJ4= +github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM= +github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc= +github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= +github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= +github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= +github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= +github.com/prometheus/common v0.73.1 h1:SZWh/j4AvhCdhX8jvYSnxvPxhWlC9QZkjJ+tOrEr7kU= +github.com/prometheus/common v0.73.1/go.mod h1:I9aA/Ukz9s1olOobh8KtCkU7B1mQPQsB9UvQPsUQ1Dk= +github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4= +github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 h1:UFpxOpYPmMNUtOWhdb+nC1WELIgVf8z9higURrbzYU4= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0/go.mod h1:YBGjxe3lt0jtXoEXxGrGhv/jM7oUBUDVK7zhAvNyEjc= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= +go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= +go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= +go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw= +go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= -golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= -golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= -golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= -golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= -google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a h1:nwKuGPlUAt+aR+pcrkfFRrTU1BVrSmYyYMxYbUIVHr0= -google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a/go.mod h1:3kWAYMk1I75K4vykHtKt2ycnOgpA6974V7bREqbsenU= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a h1:51aaUVRocpvUOSQKM6Q7VuoaktNIaMCLuhZB6DKksq4= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a/go.mod h1:uRxBH1mhmO8PGhU89cMcHaXKZqO+OfakD8QQO0oYwlQ= -google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= -google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= -google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= -google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= +go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c h1:ofk4SEqvpf6M5VWh88xRp42IYgdVOh7gffebnDj3OqU= +google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c/go.mod h1:OzYcNQzaMRKcOFRMtyLzG/cfW1SmS2eh+7UmOLLFblk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c h1:XXChExL+Tm7Ubp0x0VXUEncPLHrkXIgoVWqnxmKNbAA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= +google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= diff --git a/http.go b/http.go new file mode 100644 index 0000000..34dfb85 --- /dev/null +++ b/http.go @@ -0,0 +1,147 @@ +package obsx + +import ( + "net/http" + "strconv" + "time" + + "github.com/prometheus/client_golang/prometheus" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/propagation" + semconv "go.opentelemetry.io/otel/semconv/v1.26.0" + "go.opentelemetry.io/otel/trace" +) + +// HTTPMiddleware returns server middleware that traces every request +// (continuing the trace from incoming headers) and, when m is not nil, records +// the http_requests_total{method,route,status} counter and the +// http_request_duration_seconds{method,route} histogram. +// +// The route is the matched http.ServeMux pattern (Request.Pattern), so wrap +// the mux itself; unmatched requests are reported as route "unmatched". +// Call it once per Metrics: the metrics are registered on each call. +func HTTPMiddleware(m *Metrics) func(http.Handler) http.Handler { + var requests *prometheus.CounterVec + var duration *prometheus.HistogramVec + if m != nil { + requests = m.Counter("http_requests_total", "Total HTTP requests served.", "method", "route", "status") + duration = m.Histogram("http_request_duration_seconds", "HTTP request duration in seconds.", nil, "method", "route") + } + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + method := knownMethod(r.Method) + ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header)) + ctx, span := otel.Tracer(tracerName).Start(ctx, method, + trace.WithSpanKind(trace.SpanKindServer), + trace.WithAttributes(semconv.HTTPRequestMethodKey.String(method), semconv.URLPath(r.URL.Path)), + ) + defer span.End() + + sw := &statusWriter{ResponseWriter: w, status: http.StatusOK} + r = r.WithContext(ctx) + defer func() { + // A panic propagates to net/http, which answers 500 or drops the connection. + p := recover() + if p != nil { + sw.status = http.StatusInternalServerError + } + route := r.Pattern // set by ServeMux on this request during ServeHTTP + if route == "" { + route = "unmatched" + } else { + span.SetName(route) + span.SetAttributes(semconv.HTTPRoute(route)) + } + span.SetAttributes(semconv.HTTPResponseStatusCode(sw.status)) + if sw.status >= 500 { + span.SetStatus(codes.Error, http.StatusText(sw.status)) + } + if m != nil { + requests.WithLabelValues(method, route, strconv.Itoa(sw.status)).Inc() + duration.WithLabelValues(method, route).Observe(time.Since(start).Seconds()) + } + if p != nil { + panic(p) + } + }() + next.ServeHTTP(sw, r) + }) + } +} + +// knownMethod bounds label cardinality: clients can send arbitrary methods. +func knownMethod(m string) string { + switch m { + case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, + http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace: + return m + } + return "OTHER" +} + +type statusWriter struct { + http.ResponseWriter + status int + wrote bool +} + +func (w *statusWriter) WriteHeader(code int) { + if !w.wrote { + w.status, w.wrote = code, true + } + w.ResponseWriter.WriteHeader(code) +} + +func (w *statusWriter) Write(b []byte) (int, error) { + w.wrote = true + return w.ResponseWriter.Write(b) +} + +// Flush keeps streaming handlers (SSE) working through the wrapper. +func (w *statusWriter) Flush() { + if f, ok := w.ResponseWriter.(http.Flusher); ok { + f.Flush() + } +} + +// Unwrap gives http.ResponseController access to Hijack, deadlines, etc. +func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +// HTTPTransport wraps base (nil means http.DefaultTransport) so that every +// outgoing request gets a client span and carries the trace context headers. +func HTTPTransport(base http.RoundTripper) http.RoundTripper { + if base == nil { + base = http.DefaultTransport + } + return transport{base} +} + +type transport struct{ base http.RoundTripper } + +// shortcut: the span ends when response headers arrive, not when the body is +// fully read; wrap resp.Body if body transfer time must be in the span. +func (t transport) RoundTrip(r *http.Request) (*http.Response, error) { + method := knownMethod(r.Method) + ctx, span := otel.Tracer(tracerName).Start(r.Context(), method, + trace.WithSpanKind(trace.SpanKindClient), + trace.WithAttributes(semconv.HTTPRequestMethodKey.String(method), semconv.ServerAddress(r.URL.Host)), + ) + defer span.End() + + r = r.Clone(ctx) // RoundTrippers must not modify the caller's request + otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(r.Header)) + + resp, err := t.base.RoundTrip(r) + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, err.Error()) + return nil, err + } + span.SetAttributes(semconv.HTTPResponseStatusCode(resp.StatusCode)) + if resp.StatusCode >= 400 { + span.SetStatus(codes.Error, http.StatusText(resp.StatusCode)) + } + return resp, nil +} diff --git a/http_test.go b/http_test.go new file mode 100644 index 0000000..24fe8e9 --- /dev/null +++ b/http_test.go @@ -0,0 +1,136 @@ +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]) + } +} diff --git a/log.go b/log.go new file mode 100644 index 0000000..4fbde96 --- /dev/null +++ b/log.go @@ -0,0 +1,33 @@ +package obsx + +import ( + "context" + "log/slog" + + "go.opentelemetry.io/otel/trace" +) + +// LogHandler wraps h so that records logged with a context carrying a span +// (slog.InfoContext and friends) get trace_id and span_id attributes, +// linking logs to traces. +func LogHandler(h slog.Handler) slog.Handler { return logHandler{h} } + +type logHandler struct{ slog.Handler } + +func (h logHandler) Handle(ctx context.Context, r slog.Record) error { + if sc := trace.SpanContextFromContext(ctx); sc.IsValid() { + r.AddAttrs( + slog.String("trace_id", sc.TraceID().String()), + slog.String("span_id", sc.SpanID().String()), + ) + } + return h.Handler.Handle(ctx, r) +} + +func (h logHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return logHandler{h.Handler.WithAttrs(attrs)} +} + +func (h logHandler) WithGroup(name string) slog.Handler { + return logHandler{h.Handler.WithGroup(name)} +} diff --git a/tracer.go b/tracer.go index d248fc8..a12e73f 100644 --- a/tracer.go +++ b/tracer.go @@ -4,7 +4,9 @@ import ( "context" "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" + "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.26.0" @@ -15,8 +17,18 @@ import ( type TracerConfig struct { ServiceName string ServiceVersion string - Endpoint string // OTLP gRPC endpoint, e.g. "localhost:4317" - Sampler float64 // sampling ratio, default: 1.0 (sample everything) + // Endpoint is the OTLP gRPC endpoint, e.g. "localhost:4317". When empty, + // the standard OTEL_EXPORTER_OTLP_* environment variables apply. + Endpoint string + // Insecure disables TLS for the OTLP connection (local collectors, sidecars). + Insecure bool + // Headers are sent with every export request, e.g. for authentication. + Headers map[string]string + // Sampler is the ratio of root traces to sample, default: 1.0 (everything). + // Child spans always follow the decision of their parent. + Sampler float64 + // Attributes are extra resource attributes, e.g. deployment environment. + Attributes []attribute.KeyValue } func (c *TracerConfig) defaults() { @@ -25,43 +37,60 @@ func (c *TracerConfig) defaults() { } } -// SetupTracer initializes an OpenTelemetry tracer provider with OTLP gRPC exporter. -// Returns a shutdown function that must be called on application exit. +// SetupTracer initializes an OpenTelemetry tracer provider with an OTLP gRPC +// exporter and installs it, together with W3C TraceContext and Baggage +// propagators, as the OpenTelemetry globals. +// Returns a shutdown function that must be called on application exit to +// flush pending spans. func SetupTracer(ctx context.Context, cfg TracerConfig) (shutdown func(context.Context) error, err error) { cfg.defaults() - exporter, err := otlptracegrpc.New(ctx, - otlptracegrpc.WithEndpoint(cfg.Endpoint), - otlptracegrpc.WithInsecure(), - ) + var opts []otlptracegrpc.Option + if cfg.Endpoint != "" { + opts = append(opts, otlptracegrpc.WithEndpoint(cfg.Endpoint)) + } + if cfg.Insecure { + opts = append(opts, otlptracegrpc.WithInsecure()) + } + if len(cfg.Headers) > 0 { + opts = append(opts, otlptracegrpc.WithHeaders(cfg.Headers)) + } + exporter, err := otlptracegrpc.New(ctx, opts...) if err != nil { return nil, err } - attrs := []resource.Option{ - resource.WithAttributes(semconv.ServiceName(cfg.ServiceName)), - } + attrs := append([]attribute.KeyValue{semconv.ServiceName(cfg.ServiceName)}, cfg.Attributes...) if cfg.ServiceVersion != "" { - attrs = append(attrs, resource.WithAttributes(semconv.ServiceVersion(cfg.ServiceVersion))) + attrs = append(attrs, semconv.ServiceVersion(cfg.ServiceVersion)) } - - res, err := resource.New(ctx, attrs...) + res, err := resource.New(ctx, + resource.WithFromEnv(), // OTEL_RESOURCE_ATTRIBUTES; config below wins + resource.WithTelemetrySDK(), + resource.WithAttributes(attrs...), + ) if err != nil { + _ = exporter.Shutdown(ctx) return nil, err } tp := sdktrace.NewTracerProvider( sdktrace.WithBatcher(exporter), sdktrace.WithResource(res), - sdktrace.WithSampler(sdktrace.TraceIDRatioBased(cfg.Sampler)), + sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(cfg.Sampler))), ) otel.SetTracerProvider(tp) + otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator( + propagation.TraceContext{}, propagation.Baggage{}, + )) return tp.Shutdown, nil } +const tracerName = "git.codelab.vc/pkg/obsx" + // StartSpan starts a new span using the global tracer provider. func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) { - return otel.Tracer("obsx").Start(ctx, name, opts...) + return otel.Tracer(tracerName).Start(ctx, name, opts...) } diff --git a/tracer_test.go b/tracer_test.go index c68b855..2faa36b 100644 --- a/tracer_test.go +++ b/tracer_test.go @@ -39,6 +39,9 @@ func TestSetupTracer_SetsGlobalProvider(t *testing.T) { if _, ok := tp.(*sdktrace.TracerProvider); !ok { t.Errorf("expected *sdktrace.TracerProvider, got %T", tp) } + if f := otel.GetTextMapPropagator().Fields(); len(f) == 0 { + t.Error("expected a global propagator to be installed") + } } func TestSetupTracer_DefaultSampler(t *testing.T) {