Update documentation for the observability toolkit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
M.ShakhmatovandClaude Opus 5.5 committed 2026-11-15 16:40:52 +03:00
1 parent 2bd9def584
commit b53a6a6c30
7 files changed
+315 -198

No files matched your search

+61 -48
View File
@@ -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