Release v1.0.0: HTTP instrumentation, slog correlation, TLS by default
CI / test (push) Successful in 1m17s
Publish / publish (push) Successful in 1m24s

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>
This commit is contained in:
Aleksey ShakhmatovandClaude committed 2026-11-10 20:20:09 +03:00
1 parent 362267470e
commit 2c83b28342
15 files changed
+695 -119

No files matched your search

+52 -9
View File
@@ -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 |
|--------|--------|
| `<ns>_http_requests_total` | `method`, `route`, `status` |
| `<ns>_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).