Concurrent checks with per-check timeouts and panic recovery, HTTP handlers, grpc.health.v1 server, SetReady for graceful shutdown and the health_check_status metric. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
obsx
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.
go get git.codelab.vc/pkg/obsx
Quick start
// Tracing
shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{
ServiceName: "my-service",
ServiceVersion: "1.0.0",
Endpoint: "localhost:4317",
Insecure: true, // plaintext; TLS is the default
Sampler: 1.0, // sample everything
})
if err != nil {
log.Fatal(err)
}
defer shutdown(ctx)
// Metrics
metrics := obsx.NewMetrics(obsx.MetricsConfig{
Namespace: "myapp",
Subsystem: "http",
})
reqCounter := metrics.Counter("requests_total", "Total HTTP requests", "method", "status")
latency := metrics.Histogram("request_duration_seconds", "Request latency", nil, "method")
// 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 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. |
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 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.
shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{
ServiceName: "orders-api",
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:
ctx, span := obsx.StartSpan(ctx, "process-order")
defer span.End()
Metrics
NewMetrics creates a fresh Prometheus registry (isolated from the global default) pre-loaded with process and Go runtime collectors. All metrics created through the factory inherit the configured namespace and subsystem.
m := obsx.NewMetrics(obsx.MetricsConfig{Namespace: "myapp", Subsystem: "db"})
// Counter
queries := m.Counter("queries_total", "Total queries executed", "operation")
queries.WithLabelValues("select").Inc()
// Histogram (nil buckets = prometheus.DefBuckets)
latency := m.Histogram("query_duration_seconds", "Query latency", nil, "operation")
// Gauge
conns := m.Gauge("connections_active", "Active connections", "pool")
// HTTP handler for /metrics endpoint
http.Handle("/metrics", m.Handler())
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 |
|---|---|
<ns>_http_requests_total |
method, route, status |
<ns>_http_request_duration_seconds |
method, route |
handler := obsx.HTTPMiddleware(metrics)(mux) // pass nil for tracing only
HTTPTransport instruments outgoing requests with a client span and injects the trace context:
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:
slog.SetDefault(slog.New(obsx.LogHandler(slog.NewJSONHandler(os.Stderr, nil))))
slog.InfoContext(ctx, "order created")
Requirements
Go 1.26+, OpenTelemetry Go, Prometheus client_golang.