# obsx 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 ``` ## Quick start ```go 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()) } ``` 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() }, }) ``` ## Dashboards and alerts Because metric names are uniform, the repository ships ready-to-use monitoring for any obsx service: - [`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. 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 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()...) ``` `obsx.NewTraceHandler(h)` adds trace correlation to any existing `slog.Handler`. 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 (`_http_requests_total`, `_http_request_duration_seconds`). The API is stable since v1.0.0 — see [CHANGELOG.md](CHANGELOG.md). ## Behavior notes - `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), [gRPC-Go](https://github.com/grpc/grpc-go).