Update documentation for the observability toolkit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2bd9def584
commit
b53a6a6c30
7 files changed
+315
-198
No files matched your search
@@ -4,72 +4,84 @@ Universal guide for AI coding agents working with this codebase.
|
||||
|
||||
## Overview
|
||||
|
||||
`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.
|
||||
`git.codelab.vc/pkg/obsx` is an observability toolkit for Go microservices: slog logging with trace correlation, OpenTelemetry tracing, Prometheus metrics, health checks, an admin HTTP server, and ready-made instrumentation for HTTP/gRPC servers and clients. The main design goal is **uniformity**: every service exposes the same metric names, log fields and endpoints.
|
||||
|
||||
## Package map
|
||||
|
||||
```
|
||||
obsx/ Root — single package
|
||||
obsx/ Root package (single package)
|
||||
├── doc.go Package documentation
|
||||
├── tracer.go SetupTracer, StartSpan, TracerConfig
|
||||
├── metrics.go Metrics factory, NewMetrics, Counter/Histogram/Gauge, Handler
|
||||
├── http.go HTTPMiddleware (server), HTTPTransport (client)
|
||||
└── log.go LogHandler (slog trace correlation)
|
||||
├── observer.go Observer, New, Track, HTTP/gRPC helpers, Shutdown
|
||||
├── config.go Config, AdminConfig, defaults, WithEnv, BuildInfo
|
||||
├── 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)
|
||||
├── httpserver.go NewHTTPMiddleware, responseWriter, route detection
|
||||
├── httpclient.go NewHTTPTransport
|
||||
├── grpc.go NewGRPCInterceptors (server/client, unary/stream)
|
||||
├── health.go Health, checks, HTTP handlers, grpc.health.v1 server
|
||||
├── admin.go Observer.AdminHandler, LogLevelHandler
|
||||
├── examples/service/ Runnable example service
|
||||
└── deploy/ Grafana dashboard + Prometheus alerts for built-in metrics
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────┐
|
||||
│ obsx │
|
||||
└──────────┬───────────┘
|
||||
│
|
||||
┌───────────────┴───────────────┐
|
||||
│ │
|
||||
┌──────┴──────┐ ┌──────┴──────┐
|
||||
│ Tracing │ │ Metrics │
|
||||
└──────┬──────┘ └──────┬──────┘
|
||||
│ │
|
||||
SetupTracer() NewMetrics()
|
||||
│ │
|
||||
▼ ▼
|
||||
OTLP gRPC exporter prometheus.Registry
|
||||
TracerProvider (process + Go collectors)
|
||||
(global via otel.Set) │
|
||||
│ Counter / Histogram / Gauge
|
||||
▼ │
|
||||
StartSpan() Handler() → /metrics
|
||||
obsx.New(ctx, Config)
|
||||
│
|
||||
┌──────────────┬────────────────┼───────────────┬──────────────┐
|
||||
▼ ▼ ▼ ▼ ▼
|
||||
NewLogger newTracerProvider NewMetrics NewHealth admin server
|
||||
(slog JSON (OTLP grpc/http, (isolated reg, (liveness, (/metrics, /healthz,
|
||||
+ Trace- ParentBased go+process, readiness, /readyz, /buildinfo,
|
||||
Handler) sampler) build_info) gRPC health) /loglevel, pprof)
|
||||
│ │ │
|
||||
└──────────────┴───────┬────────┘
|
||||
▼
|
||||
Observer.HTTPMiddleware / HTTPClient / GRPC*Options / Track
|
||||
(thin wrappers over NewHTTPMiddleware, NewHTTPTransport,
|
||||
NewGRPCInterceptors with the Observer's components)
|
||||
```
|
||||
|
||||
## Common tasks
|
||||
|
||||
### Add new built-in instrumentation (e.g., message queue consumer)
|
||||
|
||||
1. Create a `<Thing>Config` struct with `Metrics *Metrics`, `Logger *slog.Logger`, `TracerProvider`, `Propagator` and a `defaults()` method (globals when nil)
|
||||
2. Create metrics through `cfg.Metrics.base()` so names have no namespace; follow `<area>_<role>_requests_total` / `_request_duration_seconds` naming
|
||||
3. Record latency with `observe(ctx, ...)` to attach exemplars
|
||||
4. Add an `Observer` wrapper method, a metric to the README/doc.go reference tables, and panels/alerts in `deploy/`
|
||||
|
||||
### Add a new metric type (e.g., Summary)
|
||||
|
||||
1. Add a method to `Metrics` struct in `metrics.go`
|
||||
2. Create the Prometheus collector with `m.cfg.Namespace` / `m.cfg.Subsystem`
|
||||
3. Register via `m.registry.MustRegister()`
|
||||
4. Return the collector
|
||||
1. Add a method to `Metrics` in `metrics.go` using `m.cfg.Namespace` / `m.cfg.Subsystem`
|
||||
2. Register via `register(m.registry, ...)` (idempotent), not `MustRegister`
|
||||
|
||||
### Change the trace exporter (e.g., HTTP instead of gRPC)
|
||||
### Add an environment variable
|
||||
|
||||
1. Replace `otlptracegrpc.New` in `SetupTracer` with the desired exporter
|
||||
2. Update `TracerConfig` fields if the new exporter needs different options
|
||||
3. Keep the same return signature (`shutdown func(context.Context) error`)
|
||||
Add an `env*` call in `Config.WithEnv` (`config.go`), document it in the doc comment and the README table, extend `TestConfig_WithEnv`.
|
||||
|
||||
### Add custom resource attributes to traces
|
||||
### Regenerate the Grafana dashboard
|
||||
|
||||
1. Append additional `resource.WithAttributes(...)` options to the `attrs` slice in `SetupTracer`
|
||||
2. Use `semconv` constants where possible
|
||||
The dashboard JSON is hand-maintainable; keep the `job` variable and `$__rate_interval` usage consistent across panels.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **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
|
||||
- **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`
|
||||
- **Globals**: `New` sets `slog.Default`, the global tracer provider, propagator and OTel error handler — only after everything that can fail succeeded. `SetupTracer` sets provider + propagator. Tests must restore globals (`newTestObserver` does).
|
||||
- **Built-in metric names ignore Namespace** by design (`Metrics.base()`); user metrics via `o.Metrics()` keep it.
|
||||
- **Batching**: `New`/`SetupTracer` use a batch span processor; tests call `ForceFlush` (`flushSpans`) before reading an in-memory exporter.
|
||||
- **No endpoint = no export**: with an empty `Tracing.Endpoint` and no `OTEL_EXPORTER_OTLP_*ENDPOINT`, the provider has no exporter but still creates spans (log correlation, propagation).
|
||||
- **Sampler**: `<= 0` means 1.0; sampling is `ParentBased(TraceIDRatioBased)`. Use `Disabled` to turn tracing off.
|
||||
- **TLS by default**: the OTLP connection is plaintext only with `TracerConfig.Insecure: true` (or `OBSX_TRACING_INSECURE=true`); `TLS` supplies a custom `tls.Config`.
|
||||
- **Stable API**: v1 is stable — do not break it; record changes in `CHANGELOG.md`.
|
||||
- **Tracer name**: all instrumentation shares the scope `git.codelab.vc/pkg/obsx`.
|
||||
- **Route detection**: default `RouteFunc` reads `r.Pattern`; when the middleware wraps an `*http.ServeMux` directly it falls back to `mux.Handler(r)`. Other routers need `RouteFunc`.
|
||||
- **Panics** are recorded and re-raised (HTTP middleware, gRPC server interceptors, `Track`).
|
||||
- **Admin shutdown** waits at most 1s, then closes connections; tracer flush happens first.
|
||||
- **Idempotent registration**: identical metric definitions return the existing collector; conflicting ones panic.
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -79,12 +91,13 @@ go test ./... # all tests
|
||||
go test -race ./... # tests with race detector
|
||||
go test -v -run TestName ./... # single test
|
||||
go vet ./... # static analysis
|
||||
go run ./examples/service # example service on :8080, admin on :9090
|
||||
```
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Struct-based Config** with `defaults()` method for zero-value defaults
|
||||
- **Isolated Prometheus registry** — each `Metrics` instance has its own registry
|
||||
- **stdlib only** testing — no testify, no gomock
|
||||
- **No functional options** — direct struct configuration
|
||||
- **Shutdown function** — `SetupTracer` returns a shutdown callback, caller is responsible for calling it
|
||||
- **Struct-based configs** with `defaults()` methods; no functional options
|
||||
- **Explicit dependencies** in standalone constructors; `Observer` wires them
|
||||
- **Isolated Prometheus registry** per `Metrics`
|
||||
- **stdlib only** testing — no testify, no gomock; gRPC tests use `bufconn` with the health service
|
||||
- **Bounded cardinality** — route templates, normalized methods, never raw paths or IDs as labels
|
||||
@@ -8,6 +8,10 @@
|
||||
- `Trace`, `RecordError`, `TraceID` helpers.
|
||||
- `Endpoint` accepts URLs (`https://collector:4318`).
|
||||
- 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.
|
||||
- `deploy/` — Grafana dashboard and Prometheus alerts; `examples/service`.
|
||||
- Metrics: idempotent registration, `Sub`, `GaugeFunc`, `CounterFunc`, `RegisterDBStats`, OpenMetrics handler with trace exemplars.
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -8,39 +8,37 @@ go test ./... # all tests
|
||||
go test -race ./... # tests with race detector
|
||||
go test -v -run TestName ./... # single test
|
||||
go vet ./... # static analysis
|
||||
go run ./examples/service # example service (:8080, admin :9090)
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
- **Module**: `git.codelab.vc/pkg/obsx`, Go 1.26, depends on OpenTelemetry and Prometheus client_golang
|
||||
- **Single package** `obsx`
|
||||
- **Module**: `git.codelab.vc/pkg/obsx`, Go 1.26, depends on OpenTelemetry, Prometheus client_golang and gRPC-Go
|
||||
- **Single package** `obsx` (+ `examples/service`, `deploy/` with Grafana dashboard and Prometheus alerts)
|
||||
|
||||
### Core patterns
|
||||
|
||||
- **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
|
||||
- **Registry()** — exposes the underlying `*prometheus.Registry` for direct access
|
||||
|
||||
### Tracer lifecycle
|
||||
|
||||
- `SetupTracer` returns `shutdown func(context.Context) error` — must be called to flush pending spans
|
||||
- Shutdown is the `TracerProvider.Shutdown` method directly
|
||||
- **New / Observer** — one call wires logger, tracer provider, metrics, health and optional admin server; `Shutdown` flushes spans and stops the admin server
|
||||
- **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
|
||||
- **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
|
||||
- **Health** — liveness/readiness checks with timeouts, HTTP handlers, `grpc.health.v1` server, `SetReady`
|
||||
- **AdminHandler** — `/metrics`, `/healthz`, `/livez`, `/readyz`, `/buildinfo`, `/loglevel`, `/debug/pprof/`
|
||||
|
||||
## Conventions
|
||||
|
||||
- Struct-based configs (`TracerConfig`, `MetricsConfig`) with `defaults()` methods
|
||||
- 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
|
||||
- Struct-based configs with `defaults()` methods; no functional options
|
||||
- Public API is stable since v1.0.0 — no breaking changes; record changes in `CHANGELOG.md`
|
||||
- Built-in metric names are fixed (no namespace) so dashboards/alerts in `deploy/` work for every service — update `deploy/`, README and doc.go when adding or renaming them
|
||||
- Isolated Prometheus registry — not the global default
|
||||
- `nil` buckets in `Histogram()` default to `prometheus.DefBuckets`
|
||||
- Bounded label cardinality: route templates, `OTHER` for unknown methods, `unmatched` for unknown routes
|
||||
- stdlib-only tests; restore otel/slog globals in tests that call `New` or `SetupTracer`
|
||||
|
||||
## See also
|
||||
|
||||
- `AGENTS.md` — universal AI agent guide with package map and common tasks
|
||||
- `AGENTS.md` — package map, common tasks, gotchas
|
||||
@@ -1,6 +1,6 @@
|
||||
# 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](CHANGELOG.md).
|
||||
Observability toolkit for Go microservices. One call wires **logs, traces, metrics, health checks and an admin endpoint**; one line instruments HTTP and gRPC servers and clients. Every service gets the same metric names, log fields and endpoints, so a single dashboard and a single set of alerts cover the whole fleet.
|
||||
|
||||
```
|
||||
go get git.codelab.vc/pkg/obsx
|
||||
@@ -9,129 +9,195 @@ go get git.codelab.vc/pkg/obsx
|
||||
## Quick start
|
||||
|
||||
```go
|
||||
// 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)
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
o, err := obsx.New(ctx, obsx.Config{
|
||||
ServiceName: "orders",
|
||||
ServiceVersion: "1.4.0",
|
||||
Environment: "production",
|
||||
Tracing: obsx.TracerConfig{Endpoint: "otel-collector:4317", Insecure: true, Sampler: 0.1},
|
||||
Admin: obsx.AdminConfig{Addr: ":9090"},
|
||||
}.WithEnv()) // OBSX_* environment variables override the values above
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer o.Shutdown(context.Background()) // flushes spans, stops the admin server
|
||||
|
||||
o.Health().AddReadinessCheck("postgres", db.PingContext)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
err := o.Track(r.Context(), "db.get_order", func(ctx context.Context) error {
|
||||
return db.QueryRowContext(ctx, "...").Scan(&order)
|
||||
})
|
||||
if err != nil {
|
||||
slog.ErrorContext(r.Context(), "get order", "error", err) // includes trace_id
|
||||
}
|
||||
})
|
||||
|
||||
srv := &http.Server{Addr: ":8080", Handler: o.HTTPMiddleware(mux)}
|
||||
go srv.ListenAndServe()
|
||||
|
||||
<-ctx.Done()
|
||||
o.Health().SetReady(false) // load balancers stop sending traffic
|
||||
srv.Shutdown(context.Background())
|
||||
}
|
||||
defer shutdown(ctx)
|
||||
```
|
||||
|
||||
// Metrics
|
||||
metrics := obsx.NewMetrics(obsx.MetricsConfig{
|
||||
Namespace: "myapp",
|
||||
Subsystem: "http",
|
||||
A runnable version lives in [`examples/service`](examples/service/main.go).
|
||||
|
||||
## What you get
|
||||
|
||||
| Area | Provided by `obsx.New` |
|
||||
|------|------------------------|
|
||||
| **Logs** | JSON `slog` logger installed as `slog.Default`, with `service`/`version`/`env` on every record and `trace_id`/`span_id` for `*Context` calls. Level changeable at runtime. |
|
||||
| **Traces** | OpenTelemetry provider with OTLP gRPC or HTTP export, parent-based ratio sampling, W3C TraceContext + Baggage propagation, resource with service/host/instance attributes. Without an endpoint, spans are still created so trace IDs appear in logs. |
|
||||
| **Metrics** | Isolated Prometheus registry with Go runtime and process collectors, `service_build_info`, trace exemplars on latency histograms. |
|
||||
| **Health** | Liveness and readiness checks run concurrently with timeouts; HTTP (`/healthz`, `/readyz`) and gRPC (`grpc.health.v1`) servers. |
|
||||
| **Admin server** | `/metrics`, `/healthz`, `/livez`, `/readyz`, `/buildinfo`, `/loglevel`, `/debug/pprof/` on an internal port. |
|
||||
|
||||
| Instrumentation | Usage |
|
||||
|-----------------|-------|
|
||||
| HTTP server | `o.HTTPMiddleware(handler)` or `router.Use(o.HTTPMiddleware)` |
|
||||
| HTTP client | `o.HTTPClient()` or `o.HTTPTransport(base)` |
|
||||
| gRPC server | `grpc.NewServer(o.GRPCServerOptions()...)` |
|
||||
| gRPC client | `grpc.NewClient(target, o.GRPCDialOptions()...)` |
|
||||
| Any operation (DB, cache, queue, job) | `o.Track(ctx, "db.get_order", fn)` |
|
||||
| Custom spans | `o.Start(ctx, name)`, `obsx.Trace(ctx, name, fn)`, `obsx.RecordError(ctx, err)` |
|
||||
| Business metrics | `o.Metrics().Counter(...)`, `.Histogram(...)`, `.Gauge(...)`, `.GaugeFunc(...)`, `.Sub("db")` |
|
||||
| DB pool stats | `o.Metrics().RegisterDBStats(db, "main")` |
|
||||
|
||||
## Metrics reference
|
||||
|
||||
Built-in metrics ignore `MetricsConfig.Namespace` on purpose: names are identical in every service. Your own metrics created via `o.Metrics()` use the namespace.
|
||||
|
||||
| Metric | Type | Labels |
|
||||
|--------|------|--------|
|
||||
| `http_server_requests_total` | counter | `method`, `route`, `code` |
|
||||
| `http_server_request_duration_seconds` | histogram | `method`, `route`, `code` |
|
||||
| `http_server_requests_in_flight` | gauge | |
|
||||
| `http_client_requests_total` | counter | `method`, `host`, `code` (`error` on transport failure) |
|
||||
| `http_client_request_duration_seconds` | histogram | `method`, `host`, `code` |
|
||||
| `grpc_server_requests_total` | counter | `service`, `method`, `code` |
|
||||
| `grpc_server_request_duration_seconds` | histogram | `service`, `method`, `code` |
|
||||
| `grpc_server_requests_in_flight` | gauge | |
|
||||
| `grpc_client_requests_total` | counter | `service`, `method`, `code` |
|
||||
| `grpc_client_request_duration_seconds` | histogram | `service`, `method`, `code` |
|
||||
| `operation_duration_seconds` | histogram | `operation`, `status` (`ok`/`error`) |
|
||||
| `health_check_status` | gauge | `check`, `kind` (`liveness`/`readiness`) |
|
||||
| `service_build_info` | gauge | `service`, `version`, `environment`, `revision`, `go_version` |
|
||||
| `go_*`, `process_*` | | Go runtime and process collectors |
|
||||
| `go_sql_*` | | `db_name`, via `RegisterDBStats` |
|
||||
|
||||
Cardinality is bounded: `route` is the router template (`/orders/{id}`), never the raw path; unknown routes are `unmatched`; non-standard HTTP methods become `OTHER`.
|
||||
|
||||
**Routes.** With `http.ServeMux` (Go 1.22+ patterns) routes are detected automatically. For other routers set `RouteFunc`:
|
||||
|
||||
```go
|
||||
obsx.NewHTTPMiddleware(obsx.HTTPServerConfig{
|
||||
Metrics: o.Metrics(),
|
||||
RouteFunc: func(r *http.Request) string {
|
||||
return chi.RouteContext(r.Context()).RoutePattern()
|
||||
},
|
||||
})
|
||||
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
|
||||
## Dashboards and alerts
|
||||
|
||||
| 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. |
|
||||
Because metric names are uniform, the repository ships ready-to-use monitoring for any obsx service:
|
||||
|
||||
## Tracing
|
||||
- [`deploy/grafana/obsx-service.json`](deploy/grafana/obsx-service.json) — Grafana dashboard: build info, health, HTTP/gRPC RED metrics with trace exemplars, dependencies, tracked operations, Go runtime, DB pool. Select services with the `job` variable.
|
||||
- [`deploy/prometheus/alerts.yml`](deploy/prometheus/alerts.yml) — alerting rules: 5xx/server-error rates, p99 latency, failing dependencies, failing operations, failing health checks, restart loops.
|
||||
|
||||
`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.
|
||||
Scrape the admin port (`:9090/metrics`) of every pod.
|
||||
|
||||
## Configuration
|
||||
|
||||
`Config` is a plain struct; zero values are sensible defaults:
|
||||
|
||||
| Field | Default |
|
||||
|-------|---------|
|
||||
| `ServiceName` | executable name |
|
||||
| `ServiceVersion` | main module version from build info |
|
||||
| `Logging.Level` / `Format` / `Output` | `info` / `json` / stdout |
|
||||
| `Tracing.Endpoint` | `OTEL_EXPORTER_OTLP_ENDPOINT`; if unset, traces are not exported |
|
||||
| `Tracing.Protocol` | `grpc` (`http` for OTLP/HTTP) |
|
||||
| `Tracing.Insecure` / `TLS` | TLS with system roots; `Insecure: true` for plaintext collectors, `TLS` for a custom `tls.Config` |
|
||||
| `Tracing.Sampler` | `1.0`, parent-based |
|
||||
| `Health.Timeout` | `5s` per check |
|
||||
| `Admin.Addr` | empty — no server; mount `o.AdminHandler()` yourself |
|
||||
|
||||
`Config.WithEnv()` lets deployments override settings without code changes:
|
||||
|
||||
| Variable | Field |
|
||||
|----------|-------|
|
||||
| `OBSX_SERVICE_NAME`, `OTEL_SERVICE_NAME` | `ServiceName` |
|
||||
| `OBSX_SERVICE_VERSION` | `ServiceVersion` |
|
||||
| `OBSX_ENVIRONMENT` | `Environment` |
|
||||
| `OBSX_LOG_LEVEL`, `OBSX_LOG_FORMAT` | `Logging.Level`, `Logging.Format` |
|
||||
| `OBSX_TRACING_ENDPOINT`, `OBSX_TRACING_PROTOCOL` | `Tracing.Endpoint`, `Tracing.Protocol` |
|
||||
| `OBSX_TRACING_INSECURE` | `Tracing.Insecure` |
|
||||
| `OBSX_TRACING_SAMPLER` | `Tracing.Sampler` |
|
||||
| `OBSX_TRACING_DISABLED`, `OTEL_SDK_DISABLED` | `Tracing.Disabled` |
|
||||
| `OBSX_METRICS_NAMESPACE` | `Metrics.Namespace` |
|
||||
| `OBSX_HEALTH_TIMEOUT` | `Health.Timeout` |
|
||||
| `OBSX_ADMIN_ADDR`, `OBSX_ADMIN_DISABLE_PPROF` | `Admin.Addr`, `Admin.DisablePprof` |
|
||||
| `OBSX_DISABLE_ACCESS_LOG` | `DisableAccessLog` |
|
||||
|
||||
Standard `OTEL_EXPORTER_OTLP_*` and `OTEL_RESOURCE_ATTRIBUTES` are honored as well.
|
||||
|
||||
## Kubernetes
|
||||
|
||||
```yaml
|
||||
ports:
|
||||
- {name: http, containerPort: 8080}
|
||||
- {name: admin, containerPort: 9090}
|
||||
livenessProbe:
|
||||
httpGet: {path: /healthz, port: admin}
|
||||
readinessProbe:
|
||||
httpGet: {path: /readyz, port: admin}
|
||||
env:
|
||||
- {name: OBSX_ENVIRONMENT, value: production}
|
||||
- {name: OBSX_TRACING_ENDPOINT, value: otel-collector.observability:4317}
|
||||
- {name: OBSX_TRACING_INSECURE, value: "true"} # plaintext in-cluster collector
|
||||
```
|
||||
|
||||
Change the log level of a running pod:
|
||||
|
||||
```
|
||||
curl -X PUT 'localhost:9090/loglevel?level=debug'
|
||||
```
|
||||
|
||||
## Standalone components
|
||||
|
||||
Each building block works without `Observer` and takes its dependencies explicitly:
|
||||
|
||||
```go
|
||||
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)
|
||||
logger, levelVar := obsx.NewLogger(obsx.LogConfig{Level: "debug"})
|
||||
shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{ServiceName: "svc", Endpoint: "localhost:4317", Insecure: true})
|
||||
metrics := obsx.NewMetrics(obsx.MetricsConfig{Namespace: "myapp"})
|
||||
health := obsx.NewHealth(obsx.HealthConfig{Metrics: metrics})
|
||||
|
||||
handler := obsx.NewHTTPMiddleware(obsx.HTTPServerConfig{Metrics: metrics, Logger: logger})(mux)
|
||||
transport := obsx.NewHTTPTransport(nil, obsx.HTTPClientConfig{Metrics: metrics})
|
||||
grpcx := obsx.NewGRPCInterceptors(obsx.GRPCConfig{Metrics: metrics, Logger: logger})
|
||||
srv := grpc.NewServer(grpcx.ServerOptions()...)
|
||||
```
|
||||
|
||||
With an empty `Endpoint` the standard `OTEL_EXPORTER_OTLP_*` environment variables apply; `OTEL_RESOURCE_ATTRIBUTES` is honoured too.
|
||||
`obsx.NewTraceHandler(h)` adds trace correlation to any existing `slog.Handler`.
|
||||
|
||||
Start spans with the convenience helper:
|
||||
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).
|
||||
|
||||
```go
|
||||
ctx, span := obsx.StartSpan(ctx, "process-order")
|
||||
defer span.End()
|
||||
```
|
||||
## Behavior notes
|
||||
|
||||
## 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.
|
||||
|
||||
```go
|
||||
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:
|
||||
|
||||
```go
|
||||
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")
|
||||
```
|
||||
- `New` installs the global `slog` logger, tracer provider and propagator; `SetupTracer` installs the tracer provider and propagator.
|
||||
- Panics in HTTP/gRPC handlers and `Track` are recorded (500 / `Internal`, failed span) and re-raised.
|
||||
- Creating an already registered metric with the same name, help and labels returns the existing collector instead of panicking.
|
||||
- gRPC health-check calls are not instrumented by `Observer.GRPCInterceptors` to keep probe noise out of metrics and logs.
|
||||
- HTTP client latency is measured until response headers arrive.
|
||||
|
||||
## Requirements
|
||||
|
||||
Go 1.26+, [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), [gRPC-Go](https://github.com/grpc/grpc-go).
|
||||
@@ -66,6 +66,7 @@ func (c *Config) defaults() {
|
||||
// OBSX_LOG_FORMAT Logging.Format
|
||||
// OBSX_TRACING_ENDPOINT Tracing.Endpoint
|
||||
// OBSX_TRACING_PROTOCOL Tracing.Protocol
|
||||
// OBSX_TRACING_INSECURE Tracing.Insecure
|
||||
// OBSX_TRACING_SAMPLER Tracing.Sampler
|
||||
// OBSX_TRACING_DISABLED, OTEL_SDK_DISABLED Tracing.Disabled
|
||||
// OBSX_METRICS_NAMESPACE Metrics.Namespace
|
||||
@@ -86,6 +87,7 @@ func (c Config) WithEnv() Config {
|
||||
envString(&c.Logging.Format, "OBSX_LOG_FORMAT")
|
||||
envString(&c.Tracing.Endpoint, "OBSX_TRACING_ENDPOINT")
|
||||
envString(&c.Tracing.Protocol, "OBSX_TRACING_PROTOCOL")
|
||||
envBool(&c.Tracing.Insecure, "OBSX_TRACING_INSECURE")
|
||||
envFloat(&c.Tracing.Sampler, "OBSX_TRACING_SAMPLER")
|
||||
envBool(&c.Tracing.Disabled, "OTEL_SDK_DISABLED")
|
||||
envBool(&c.Tracing.Disabled, "OBSX_TRACING_DISABLED")
|
||||
|
||||
@@ -1,28 +1,62 @@
|
||||
// Package obsx wires observability into a Go service: tracing (OpenTelemetry),
|
||||
// metrics (Prometheus) and trace-correlated logs (log/slog).
|
||||
// Package obsx is an observability toolkit for Go microservices: structured
|
||||
// logging with trace correlation (log/slog), distributed tracing
|
||||
// (OpenTelemetry, OTLP), metrics (Prometheus), health checks and an admin
|
||||
// endpoint — set up with one call and applied the same way in every service.
|
||||
//
|
||||
// # Quick Start
|
||||
//
|
||||
// // Tracing: global tracer provider + W3C propagation
|
||||
// shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{
|
||||
// ServiceName: "my-service",
|
||||
// Endpoint: "localhost:4317",
|
||||
// Insecure: true,
|
||||
// })
|
||||
// defer shutdown(ctx)
|
||||
// o, err := obsx.New(ctx, obsx.Config{
|
||||
// ServiceName: "orders",
|
||||
// ServiceVersion: "1.4.0",
|
||||
// Environment: "production",
|
||||
// Tracing: obsx.TracerConfig{Endpoint: "otel-collector:4317", Insecure: true},
|
||||
// Admin: obsx.AdminConfig{Addr: ":9090"}, // /metrics, /healthz, /readyz, pprof
|
||||
// }.WithEnv())
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
// defer o.Shutdown(context.Background())
|
||||
//
|
||||
// // Logs carry trace_id / span_id
|
||||
// slog.SetDefault(slog.New(obsx.LogHandler(slog.NewJSONHandler(os.Stderr, nil))))
|
||||
// o.Health().AddReadinessCheck("postgres", db.PingContext)
|
||||
//
|
||||
// // Metrics
|
||||
// metrics := obsx.NewMetrics(obsx.MetricsConfig{Namespace: "myapp"})
|
||||
// mux.Handle("GET /metrics", metrics.Handler())
|
||||
// http.ListenAndServe(":8080", o.HTTPMiddleware(mux)) // HTTP server
|
||||
// client := o.HTTPClient() // HTTP client
|
||||
// srv := grpc.NewServer(o.GRPCServerOptions()...) // gRPC server
|
||||
// conn, _ := grpc.NewClient(target, o.GRPCDialOptions()...) // gRPC client
|
||||
// err = o.Track(ctx, "db.get_order", func(ctx context.Context) error { ... })
|
||||
//
|
||||
// // HTTP server spans + request metrics, and traced outgoing calls
|
||||
// handler := obsx.HTTPMiddleware(metrics)(mux)
|
||||
// client := &http.Client{Transport: obsx.HTTPTransport(nil)}
|
||||
// # Uniform telemetry
|
||||
//
|
||||
// Built-in instrumentation always produces the same metric names regardless of
|
||||
// MetricsConfig.Namespace, so one dashboard and one set of alerts (see the
|
||||
// deploy directory of the repository) cover every service:
|
||||
//
|
||||
// http_server_requests_total{method,route,code}
|
||||
// http_server_request_duration_seconds{method,route,code}
|
||||
// http_server_requests_in_flight
|
||||
// http_client_requests_total{method,host,code}
|
||||
// http_client_request_duration_seconds{method,host,code}
|
||||
// grpc_server_requests_total{service,method,code}
|
||||
// grpc_server_request_duration_seconds{service,method,code}
|
||||
// grpc_server_requests_in_flight
|
||||
// grpc_client_requests_total{service,method,code}
|
||||
// grpc_client_request_duration_seconds{service,method,code}
|
||||
// operation_duration_seconds{operation,status}
|
||||
// health_check_status{check,kind}
|
||||
// service_build_info{service,version,environment,revision,go_version}
|
||||
//
|
||||
// Latency histograms carry trace_id exemplars for sampled requests. Log
|
||||
// records written with a context (slog.InfoContext etc.) carry trace_id and
|
||||
// span_id.
|
||||
//
|
||||
// # Standalone components
|
||||
//
|
||||
// Every part can be used without an Observer: NewLogger, SetupTracer,
|
||||
// NewMetrics, NewHealth, NewHTTPMiddleware, NewHTTPTransport and
|
||||
// NewGRPCInterceptors accept explicit dependencies through config structs.
|
||||
//
|
||||
// # Stability
|
||||
//
|
||||
// The package follows semantic versioning; the v1 API is stable.
|
||||
// The package follows semantic versioning; the v1 API is stable. The v1.0.0
|
||||
// helpers HTTPMiddleware, HTTPTransport and LogHandler remain available.
|
||||
package obsx
|
||||
+1
-1
@@ -27,7 +27,7 @@ func ExampleNew() {
|
||||
ServiceName: "orders",
|
||||
ServiceVersion: "1.4.0",
|
||||
Environment: "production",
|
||||
Tracing: obsx.TracerConfig{Endpoint: "otel-collector:4317", Sampler: 0.1},
|
||||
Tracing: obsx.TracerConfig{Endpoint: "otel-collector:4317", Insecure: true, Sampler: 0.1},
|
||||
Admin: obsx.AdminConfig{Addr: ":9090"},
|
||||
}.WithEnv())
|
||||
if err != nil {
|
||||
|
||||
Reference in new issue
Block a user