Deprecate v1.0.0 HTTP and log helpers in favour of the toolkit API
CI / test (push) Successful in 1m12s
CI / test (push) Successful in 1m12s
LogHandler and HTTPTransport now delegate to NewTraceHandler and NewHTTPTransport. HTTPMiddleware keeps its v1.0.0 metric names but shares responseWriter and normalizeMethod with NewHTTPMiddleware. The package example shows obsx.New. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
b53a6a6c30
commit
8837e8d316
8 files changed
+40
-149
No files matched your search
@@ -16,8 +16,8 @@ obsx/ Root package (single package)
|
|||||||
├── logger.go LogConfig, NewLogger, ParseLevel, TraceHandler
|
├── logger.go LogConfig, NewLogger, ParseLevel, TraceHandler
|
||||||
├── tracer.go TracerConfig, SetupTracer, StartSpan, Trace, RecordError, TraceID
|
├── tracer.go TracerConfig, SetupTracer, StartSpan, Trace, RecordError, TraceID
|
||||||
├── metrics.go Metrics factory, register (idempotent), observe (exemplars)
|
├── metrics.go Metrics factory, register (idempotent), observe (exemplars)
|
||||||
├── http.go HTTPMiddleware, HTTPTransport (v1.0.0 API, kept for compatibility)
|
├── http.go HTTPMiddleware, HTTPTransport (v1.0.0 API, deprecated wrappers)
|
||||||
├── log.go LogHandler (v1.0.0 API, kept for compatibility)
|
├── log.go LogHandler (v1.0.0 API, deprecated alias of NewTraceHandler)
|
||||||
├── httpserver.go NewHTTPMiddleware, responseWriter, route detection
|
├── httpserver.go NewHTTPMiddleware, responseWriter, route detection
|
||||||
├── httpclient.go NewHTTPTransport
|
├── httpclient.go NewHTTPTransport
|
||||||
├── grpc.go NewGRPCInterceptors (server/client, unary/stream)
|
├── grpc.go NewGRPCInterceptors (server/client, unary/stream)
|
||||||
|
|||||||
+7
-1
@@ -10,12 +10,18 @@
|
|||||||
- Resource carries `service.instance.id` and host attributes.
|
- 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.
|
- `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`).
|
- `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`.
|
- `deploy/` — Grafana dashboard and Prometheus alerts; `examples/service`.
|
||||||
- Metrics: idempotent registration, `Sub`, `GaugeFunc`, `CounterFunc`, `RegisterDBStats`, OpenMetrics handler with trace exemplars.
|
- 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 (`<ns>_http_requests_total`, `<ns>_http_request_duration_seconds`).
|
||||||
|
- `HTTPTransport` → `NewHTTPTransport`; `LogHandler` → `NewTraceHandler`. Both now delegate to the new implementations.
|
||||||
|
|
||||||
### Changed
|
### 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`).
|
- Without `Endpoint` and `OTEL_EXPORTER_OTLP_*ENDPOINT`, spans are created and propagated but not exported (previously the exporter tried `localhost:4317`).
|
||||||
|
|
||||||
## v1.0.0
|
## v1.0.0
|
||||||
|
|||||||
@@ -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
|
- **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
|
- **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
|
- **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
|
- **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
|
- **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
|
- **NewHTTPMiddleware / NewHTTPTransport / NewGRPCInterceptors** — server/client instrumentation: spans, propagation, RED metrics, access logs
|
||||||
|
|||||||
@@ -188,7 +188,7 @@ srv := grpc.NewServer(grpcx.ServerOptions()...)
|
|||||||
|
|
||||||
`obsx.NewTraceHandler(h)` adds trace correlation to any existing `slog.Handler`.
|
`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 `<ns>_http_requests_total`, `<ns>_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 (`<ns>_http_requests_total`, `<ns>_http_request_duration_seconds`). The API is stable since v1.0.0 — see [CHANGELOG.md](CHANGELOG.md).
|
||||||
|
|
||||||
## Behavior notes
|
## Behavior notes
|
||||||
|
|
||||||
|
|||||||
@@ -58,5 +58,7 @@
|
|||||||
// # Stability
|
// # Stability
|
||||||
//
|
//
|
||||||
// The package follows semantic versioning; the v1 API is stable. The v1.0.0
|
// 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
|
package obsx
|
||||||
+1
-35
@@ -19,7 +19,7 @@ import (
|
|||||||
|
|
||||||
// A complete HTTP service: one call to New wires logging, tracing, metrics,
|
// A complete HTTP service: one call to New wires logging, tracing, metrics,
|
||||||
// health checks and the admin server; instrumentation is a single wrapper.
|
// 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)
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
defer stop()
|
defer stop()
|
||||||
|
|
||||||
@@ -140,37 +140,3 @@ func ExampleTrace() {
|
|||||||
})
|
})
|
||||||
_ = err
|
_ = 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))
|
|
||||||
}
|
|
||||||
@@ -20,7 +20,10 @@ import (
|
|||||||
//
|
//
|
||||||
// The route is the matched http.ServeMux pattern (Request.Pattern), so wrap
|
// The route is the matched http.ServeMux pattern (Request.Pattern), so wrap
|
||||||
// the mux itself; unmatched requests are reported as route "unmatched".
|
// 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 {
|
func HTTPMiddleware(m *Metrics) func(http.Handler) http.Handler {
|
||||||
var requests *prometheus.CounterVec
|
var requests *prometheus.CounterVec
|
||||||
var duration *prometheus.HistogramVec
|
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 func(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
method := knownMethod(r.Method)
|
method := normalizeMethod(r.Method)
|
||||||
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||||
ctx, span := otel.Tracer(tracerName).Start(ctx, method,
|
ctx, span := otel.Tracer(tracerName).Start(ctx, method,
|
||||||
trace.WithSpanKind(trace.SpanKindServer),
|
trace.WithSpanKind(trace.SpanKindServer),
|
||||||
@@ -39,109 +42,46 @@ func HTTPMiddleware(m *Metrics) func(http.Handler) http.Handler {
|
|||||||
)
|
)
|
||||||
defer span.End()
|
defer span.End()
|
||||||
|
|
||||||
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
rw := &responseWriter{ResponseWriter: w}
|
||||||
r = r.WithContext(ctx)
|
r = r.WithContext(ctx)
|
||||||
defer func() {
|
defer func() {
|
||||||
// A panic propagates to net/http, which answers 500 or drops the connection.
|
// A panic propagates to net/http, which answers 500 or drops the connection.
|
||||||
p := recover()
|
p := recover()
|
||||||
if p != nil {
|
status := rw.status
|
||||||
sw.status = http.StatusInternalServerError
|
switch {
|
||||||
|
case p != nil:
|
||||||
|
status = http.StatusInternalServerError
|
||||||
|
case status == 0:
|
||||||
|
status = http.StatusOK
|
||||||
}
|
}
|
||||||
route := r.Pattern // set by ServeMux on this request during ServeHTTP
|
route := r.Pattern // set by ServeMux on this request during ServeHTTP
|
||||||
if route == "" {
|
if route == "" {
|
||||||
route = "unmatched"
|
route = routeUnmatched
|
||||||
} else {
|
} else {
|
||||||
span.SetName(route)
|
span.SetName(route)
|
||||||
span.SetAttributes(semconv.HTTPRoute(route))
|
span.SetAttributes(semconv.HTTPRoute(route))
|
||||||
}
|
}
|
||||||
span.SetAttributes(semconv.HTTPResponseStatusCode(sw.status))
|
span.SetAttributes(semconv.HTTPResponseStatusCode(status))
|
||||||
if sw.status >= 500 {
|
if status >= 500 {
|
||||||
span.SetStatus(codes.Error, http.StatusText(sw.status))
|
span.SetStatus(codes.Error, http.StatusText(status))
|
||||||
}
|
}
|
||||||
if m != nil {
|
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())
|
duration.WithLabelValues(method, route).Observe(time.Since(start).Seconds())
|
||||||
}
|
}
|
||||||
if p != nil {
|
if p != nil {
|
||||||
panic(p)
|
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
|
// HTTPTransport wraps base (nil means http.DefaultTransport) so that every
|
||||||
// outgoing request gets a client span and carries the trace context headers.
|
// 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 {
|
func HTTPTransport(base http.RoundTripper) http.RoundTripper {
|
||||||
if base == nil {
|
return NewHTTPTransport(base, HTTPClientConfig{})
|
||||||
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
|
|
||||||
}
|
}
|
||||||
@@ -1,33 +1,10 @@
|
|||||||
package obsx
|
package obsx
|
||||||
|
|
||||||
import (
|
import "log/slog"
|
||||||
"context"
|
|
||||||
"log/slog"
|
|
||||||
|
|
||||||
"go.opentelemetry.io/otel/trace"
|
|
||||||
)
|
|
||||||
|
|
||||||
// LogHandler wraps h so that records logged with a context carrying a span
|
// LogHandler wraps h so that records logged with a context carrying a span
|
||||||
// (slog.InfoContext and friends) get trace_id and span_id attributes,
|
// (slog.InfoContext and friends) get trace_id and span_id attributes,
|
||||||
// linking logs to traces.
|
// linking logs to traces.
|
||||||
func LogHandler(h slog.Handler) slog.Handler { return logHandler{h} }
|
//
|
||||||
|
// Deprecated: use NewTraceHandler, which LogHandler now calls.
|
||||||
type logHandler struct{ slog.Handler }
|
func LogHandler(h slog.Handler) slog.Handler { return NewTraceHandler(h) }
|
||||||
|
|
||||||
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)}
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user