diff --git a/AGENTS.md b/AGENTS.md index b35b3fb..5145008 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,8 +16,8 @@ obsx/ Root package (single package) ├── logger.go LogConfig, NewLogger, ParseLevel, TraceHandler ├── tracer.go TracerConfig, SetupTracer, StartSpan, Trace, RecordError, TraceID ├── metrics.go Metrics factory, register (idempotent), observe (exemplars) -├── http.go HTTPMiddleware, HTTPTransport (v1.0.0 API, kept for compatibility) -├── log.go LogHandler (v1.0.0 API, kept for compatibility) +├── http.go HTTPMiddleware, HTTPTransport (v1.0.0 API, deprecated wrappers) +├── log.go LogHandler (v1.0.0 API, deprecated alias of NewTraceHandler) ├── httpserver.go NewHTTPMiddleware, responseWriter, route detection ├── httpclient.go NewHTTPTransport ├── grpc.go NewGRPCInterceptors (server/client, unary/stream) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fe291e..c9539cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,12 +10,18 @@ - Resource carries `service.instance.id` and host attributes. - `New` / `Observer` — one call wires logger, tracer, metrics, health checks and the admin server; `Config.WithEnv` applies `OBSX_*` overrides. - `NewLogger`, `NewTraceHandler`; `NewHealth` (liveness/readiness, HTTP and `grpc.health.v1`). -- `NewHTTPMiddleware`, `NewHTTPTransport`, `NewGRPCInterceptors` — config-based instrumentation with fixed metric names (`http_server_*`, `http_client_*`, `grpc_*`). `HTTPMiddleware`, `HTTPTransport` and `LogHandler` are unchanged. +- `NewHTTPMiddleware`, `NewHTTPTransport`, `NewGRPCInterceptors` — config-based instrumentation with fixed metric names (`http_server_*`, `http_client_*`, `grpc_*`). - `deploy/` — Grafana dashboard and Prometheus alerts; `examples/service`. - Metrics: idempotent registration, `Sub`, `GaugeFunc`, `CounterFunc`, `RegisterDBStats`, OpenMetrics handler with trace exemplars. +### Deprecated + +- `HTTPMiddleware` → `NewHTTPMiddleware` / `Observer.HTTPMiddleware`. It keeps working with its v1.0.0 metric names (`_http_requests_total`, `_http_request_duration_seconds`). +- `HTTPTransport` → `NewHTTPTransport`; `LogHandler` → `NewTraceHandler`. Both now delegate to the new implementations. + ### Changed +- `HTTPTransport` client spans carry `server.address` without the port and add `url.full` (credentials stripped). - Without `Endpoint` and `OTEL_EXPORTER_OTLP_*ENDPOINT`, spans are created and propagated but not exported (previously the exporter tried `localhost:4317`). ## v1.0.0 diff --git a/CLAUDE.md b/CLAUDE.md index 298c630..73b8575 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,7 +22,7 @@ go run ./examples/service # example service (:8080, admin :9090) - **Config** — service identity + per-component configs; `defaults()` fills service name/version and propagates identity to `Tracing`; `WithEnv()` applies `OBSX_*` / `OTEL_*` overrides - **NewLogger / TraceHandler** — slog JSON/text logger; `TraceHandler` adds `trace_id`/`span_id` from context - **SetupTracer / newTracerProvider** — OTLP gRPC or HTTP exporter (TLS unless `Insecure`; none when no endpoint), `ParentBased(TraceIDRatioBased)` sampler, resource with service/host attrs; sets global provider + TraceContext/Baggage propagator -- **HTTPMiddleware / HTTPTransport / LogHandler** — the v1.0.0 API (`http.go`, `log.go`), kept for compatibility: metrics `http_requests_total` / `http_request_duration_seconds` under the namespace +- **HTTPMiddleware / HTTPTransport / LogHandler** — the v1.0.0 API (`http.go`, `log.go`), deprecated but must keep working: `HTTPTransport` and `LogHandler` delegate to the new implementations, `HTTPMiddleware` keeps its own metrics `http_requests_total` / `http_request_duration_seconds` under the namespace - **StartSpan / Trace / RecordError / TraceID** — span helpers on the global provider - **Metrics** — Prometheus factory with namespace/subsystem, idempotent `register`, `Sub`, `GaugeFunc`, `CounterFunc`, `RegisterDBStats`; `base()` gives a namespace-free factory for built-in metrics; `observe` attaches trace exemplars - **NewHTTPMiddleware / NewHTTPTransport / NewGRPCInterceptors** — server/client instrumentation: spans, propagation, RED metrics, access logs diff --git a/README.md b/README.md index ffb65bd..6ee6a48 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ srv := grpc.NewServer(grpcx.ServerOptions()...) `obsx.NewTraceHandler(h)` adds trace correlation to any existing `slog.Handler`. -The v1.0.0 helpers `HTTPMiddleware(metrics)`, `HTTPTransport(base)` and `LogHandler(h)` remain available and unchanged (metrics `_http_requests_total`, `_http_request_duration_seconds`). The API is stable since v1.0.0 — see [CHANGELOG.md](CHANGELOG.md). +The v1.0.0 helpers `HTTPMiddleware(metrics)`, `HTTPTransport(base)` and `LogHandler(h)` still work but are deprecated in favour of `NewHTTPMiddleware`, `NewHTTPTransport` and `NewTraceHandler`; `HTTPMiddleware` keeps its v1.0.0 metric names (`_http_requests_total`, `_http_request_duration_seconds`). The API is stable since v1.0.0 — see [CHANGELOG.md](CHANGELOG.md). ## Behavior notes diff --git a/doc.go b/doc.go index 4edfc0c..1f2b72a 100644 --- a/doc.go +++ b/doc.go @@ -58,5 +58,7 @@ // # Stability // // The package follows semantic versioning; the v1 API is stable. The v1.0.0 -// helpers HTTPMiddleware, HTTPTransport and LogHandler remain available. +// helpers HTTPMiddleware, HTTPTransport and LogHandler still work but are +// deprecated in favour of NewHTTPMiddleware, NewHTTPTransport and +// NewTraceHandler. package obsx diff --git a/example_test.go b/example_test.go index d00cb7d..2a32dbe 100644 --- a/example_test.go +++ b/example_test.go @@ -19,7 +19,7 @@ import ( // A complete HTTP service: one call to New wires logging, tracing, metrics, // health checks and the admin server; instrumentation is a single wrapper. -func ExampleNew() { +func Example() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() @@ -140,37 +140,3 @@ func ExampleTrace() { }) _ = err } - -// 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/http.go b/http.go index 34dfb85..b4f359c 100644 --- a/http.go +++ b/http.go @@ -20,7 +20,10 @@ import ( // // 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. +// +// Deprecated: use NewHTTPMiddleware (or Observer.HTTPMiddleware), which adds +// access logs, in-flight and exemplar support and uses the fleet-wide +// http_server_* metric names. HTTPMiddleware keeps its v1.0.0 metric names. func HTTPMiddleware(m *Metrics) func(http.Handler) http.Handler { var requests *prometheus.CounterVec var duration *prometheus.HistogramVec @@ -31,7 +34,7 @@ func HTTPMiddleware(m *Metrics) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() - method := knownMethod(r.Method) + method := normalizeMethod(r.Method) ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header)) ctx, span := otel.Tracer(tracerName).Start(ctx, method, trace.WithSpanKind(trace.SpanKindServer), @@ -39,109 +42,46 @@ func HTTPMiddleware(m *Metrics) func(http.Handler) http.Handler { ) defer span.End() - sw := &statusWriter{ResponseWriter: w, status: http.StatusOK} + rw := &responseWriter{ResponseWriter: w} 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 + status := rw.status + switch { + case p != nil: + status = http.StatusInternalServerError + case status == 0: + status = http.StatusOK } route := r.Pattern // set by ServeMux on this request during ServeHTTP if route == "" { - route = "unmatched" + route = routeUnmatched } 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)) + span.SetAttributes(semconv.HTTPResponseStatusCode(status)) + if status >= 500 { + span.SetStatus(codes.Error, http.StatusText(status)) } if m != nil { - requests.WithLabelValues(method, route, strconv.Itoa(sw.status)).Inc() + requests.WithLabelValues(method, route, strconv.Itoa(status)).Inc() duration.WithLabelValues(method, route).Observe(time.Since(start).Seconds()) } if p != nil { panic(p) } }() - next.ServeHTTP(sw, r) + next.ServeHTTP(rw, 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. +// +// Deprecated: use NewHTTPTransport, which HTTPTransport now calls without metrics. 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 + return NewHTTPTransport(base, HTTPClientConfig{}) } diff --git a/log.go b/log.go index 4fbde96..470d96f 100644 --- a/log.go +++ b/log.go @@ -1,33 +1,10 @@ package obsx -import ( - "context" - "log/slog" - - "go.opentelemetry.io/otel/trace" -) +import "log/slog" // 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)} -} +// +// Deprecated: use NewTraceHandler, which LogHandler now calls. +func LogHandler(h slog.Handler) slog.Handler { return NewTraceHandler(h) }