Compare commits

...
11 Commits
Author SHA1 Message Date
M.ShakhmatovandClaude Fable 5.2 c92fd9826b Harden instrumentation, health checks and the admin server
CI / test (push) Failing after 43s
- Admin pprof is opt-in (AdminConfig.EnablePprof)
- Client spans drop the URL query string; HostFunc bounds the host label
- Config.HTTP/HTTPClient/GRPC configure the Observer's instrumentation
- A panic after a partial HTTP response counts as 500
- GaugeFunc, CounterFunc and RegisterDBStats panic on duplicates
- Abandoned client gRPC streams are recorded as Canceled
- OTEL_EXPORTER_OTLP_PROTOCOL selects the protocol when unset
- Health reports are cached for 1s; hung checks are not restarted
- Environment is exported as deployment.environment.name

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 16:56:39 +03:00
M.ShakhmatovandClaude Fable 5.2 8647fdf1bb Run staticcheck and govulncheck in CI
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 16:56:39 +03:00
M.ShakhmatovandClaude Fable 5.2 8837e8d316 Deprecate v1.0.0 HTTP and log helpers in favour of the toolkit API
CI / test (push) Successful in 1m12s
LogHandler and HTTPTransport now delegate to NewTraceHandler and
NewHTTPTransport. HTTPMiddleware keeps its v1.0.0 metric names but
shares responseWriter and normalizeMethod with NewHTTPMiddleware.
The package example shows obsx.New.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 16:43:33 +03:00
M.ShakhmatovandClaude Opus 5.5 b53a6a6c30 Update documentation for the observability toolkit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:40:52 +03:00
M.ShakhmatovandClaude Opus 5.5 2bd9def584 Add Grafana dashboard and Prometheus alerts
Shared monitoring for any obsx service, built on the uniform built-in
metric names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:40:05 +03:00
M.ShakhmatovandClaude Opus 5.5 be4330a9ee Add Observer as a single entry point
obsx.New wires logger, tracer provider, metrics, health checks and the
admin server (/metrics, /healthz, /readyz, /buildinfo, /loglevel,
pprof). Adds Track for arbitrary operations, Config.WithEnv overrides,
godoc examples and a runnable example service.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:40:05 +03:00
M.ShakhmatovandClaude Opus 5.5 8398e81bc7 Add HTTP and gRPC instrumentation
HTTP server middleware, HTTP client transport and gRPC server/client
interceptors (unary and stream) providing spans, context propagation,
RED metrics with uniform names and access logs. Labels are kept
low-cardinality (route templates, normalized methods).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:39:38 +03:00
M.ShakhmatovandClaude Opus 5.5 c710afb127 Add liveness and readiness health checks
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>
2026-11-15 16:39:08 +03:00
M.ShakhmatovandClaude Opus 5.5 598ee0536d Add slog logger with trace correlation
NewLogger builds a JSON/text slog logger with a runtime-adjustable
level; TraceHandler adds trace_id and span_id from the context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:39:08 +03:00
M.ShakhmatovandClaude Opus 5.5 022db31878 Extend tracing and metrics
Tracing: OTLP gRPC/HTTP exporters with TLS and headers, parent-based
sampling, W3C TraceContext/Baggage propagation, richer resource
attributes, no-export mode without an endpoint, Disabled flag, and
Trace/RecordError/TraceID helpers.

Metrics: idempotent registration, Sub, GaugeFunc, CounterFunc,
RegisterDBStats, OpenMetrics handler with trace exemplars.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:39:08 +03:00
Aleksey ShakhmatovandClaude 2c83b28342 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>
2026-11-10 20:20:09 +03:00
35 changed files with 6258 additions and 261 deletions

No files matched your search

+6
View File
@@ -21,3 +21,9 @@ jobs:
- name: Test - name: Test
run: go test -race -count=1 ./... run: go test -race -count=1 ./...
- name: Staticcheck
run: go run honnef.co/go/tools/cmd/staticcheck@latest ./...
- name: Vulnerabilities
run: go run golang.org/x/vuln/cmd/govulncheck@latest ./...
+64 -45
View File
@@ -4,69 +4,87 @@ Universal guide for AI coding agents working with this codebase.
## Overview ## Overview
`git.codelab.vc/pkg/obsx` is a Go observability library providing Prometheus metrics and OpenTelemetry tracing setup with consistent defaults and isolated registries. `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 ## Package map
``` ```
obsx/ Root — tracing, metrics, config obsx/ Root package (single package)
├── doc.go Package documentation ├── doc.go Package documentation
├── tracer.go SetupTracer, StartSpan, TracerConfig ├── observer.go Observer, New, Track, HTTP/gRPC helpers, Shutdown
├── metrics.go Metrics factory, NewMetrics, Counter/Histogram/Gauge, Handler ├── config.go Config, AdminConfig, defaults, WithEnv, BuildInfo
└── config.go (empty — configs are co-located with their components) ├── 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, deprecated wrappers)
├── log.go LogHandler (v1.0.0 API, deprecated alias of NewTraceHandler)
├── 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 ## Architecture
``` ```
┌──────────────────────┐ obsx.New(ctx, Config)
│ obsx │ │
└──────────┬───────────┘ ┌──────────────┬────────────────┼───────────────┬──────────────┐
│ ▼ ▼ ▼ ▼ ▼
┌───────────────┴───────────────┐ NewLogger newTracerProvider NewMetrics NewHealth admin server
│ │ (slog JSON (OTLP grpc/http, (isolated reg, (liveness, (/metrics, /healthz,
┌──────┴──────┐ ┌──────┴──────┐ + Trace- ParentBased go+process, readiness, /readyz, /buildinfo,
│ Tracing │ │ Metrics │ Handler) sampler) build_info) gRPC health) /loglevel, pprof)
└──────┬──────┘ └──────┬──────┘ │ │ │
│ │ └──────────────┴───────┬────────┘
SetupTracer() NewMetrics() ▼
│ │ Observer.HTTPMiddleware / HTTPClient / GRPC*Options / Track
▼ ▼ (thin wrappers over NewHTTPMiddleware, NewHTTPTransport,
OTLP gRPC exporter prometheus.Registry NewGRPCInterceptors with the Observer's components)
TracerProvider (process + Go collectors)
(global via otel.Set) │
│ Counter / Histogram / Gauge
▼ │
StartSpan() Handler() → /metrics
``` ```
## Common tasks ## 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) ### Add a new metric type (e.g., Summary)
1. Add a method to `Metrics` struct in `metrics.go` 1. Add a method to `Metrics` in `metrics.go` using `m.cfg.Namespace` / `m.cfg.Subsystem`
2. Create the Prometheus collector with `m.cfg.Namespace` / `m.cfg.Subsystem` 2. Register via `register(m.registry, ...)` (idempotent), not `MustRegister`
3. Register via `m.registry.MustRegister()`
4. Return the collector
### Change the trace exporter (e.g., HTTP instead of gRPC) ### Add an environment variable
1. Replace `otlptracegrpc.New` in `SetupTracer` with the desired exporter Add an `env*` call in `Config.WithEnv` (`config.go`), document it in the doc comment and the README table, extend `TestConfig_WithEnv`.
2. Update `TracerConfig` fields if the new exporter needs different options
3. Keep the same return signature (`shutdown func(context.Context) error`)
### Add custom resource attributes to traces ### Regenerate the Grafana dashboard
1. Append additional `resource.WithAttributes(...)` options to the `attrs` slice in `SetupTracer` The dashboard JSON is hand-maintainable; keep the `job` variable and `$__rate_interval` usage consistent across panels.
2. Use `semconv` constants where possible
## Gotchas ## Gotchas
- **SetupTracer sets the global provider**: calling it multiple times overwrites the previous provider; the old provider is not shut down automatically - **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).
- **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 - **Built-in metric names ignore Namespace** by design (`Metrics.base()`); user metrics via `o.Metrics()` keep it.
- **Sampler default**: if `TracerConfig.Sampler` is 0 or negative, it defaults to 1.0 (sample everything), not 0 - **Batching**: `New`/`SetupTracer` use a batch span processor; tests call `ForceFlush` (`flushSpans`) before reading an in-memory exporter.
- **Insecure gRPC**: `SetupTracer` always uses `otlptracegrpc.WithInsecure()` — no TLS for the OTLP endpoint - **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).
- **StartSpan tracer name**: uses the hardcoded tracer name `"obsx"` — all spans created via this helper share the same instrumentation scope - **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. `GaugeFunc`, `CounterFunc` and `RegisterDBStats` always panic on a duplicate.
- **Observer instrumentation is configured through `Config.HTTP` / `HTTPClient` / `GRPC`**; the Observer only fills empty `Metrics`, `Logger`, `TracerProvider`.
- **Health cache**: reports are reused for `healthCacheTTL` (1s); tests needing a fresh run call `reportCache.reset()`.
- **pprof is opt-in** (`Admin.EnablePprof`); the admin server has no authentication.
## Commands ## Commands
@@ -76,12 +94,13 @@ go test ./... # all tests
go test -race ./... # tests with race detector go test -race ./... # tests with race detector
go test -v -run TestName ./... # single test go test -v -run TestName ./... # single test
go vet ./... # static analysis go vet ./... # static analysis
go run ./examples/service # example service on :8080, admin on :9090
``` ```
## Conventions ## Conventions
- **Struct-based Config** with `defaults()` method for zero-value defaults - **Struct-based configs** with `defaults()` methods; no functional options
- **Isolated Prometheus registry** — each `Metrics` instance has its own registry - **Explicit dependencies** in standalone constructors; `Observer` wires them
- **stdlib only** testing — no testify, no gomock - **Isolated Prometheus registry** per `Metrics`
- **No functional options** — direct struct configuration - **stdlib only** testing — no testify, no gomock; gRPC tests use `bufconn` with the health service
- **Shutdown function** — `SetupTracer` returns a shutdown callback, caller is responsible for calling it - **Bounded cardinality** — route templates, normalized methods, never raw paths or IDs as labels
+47
View File
@@ -0,0 +1,47 @@
# Changelog
## Unreleased
### Added
- `TracerConfig.Protocol` (`ProtocolGRPC` / `ProtocolHTTP`), `TracerConfig.TLS`, `TracerConfig.Environment`, `TracerConfig.Disabled`, `TracerConfig.Exporter`.
- `Trace`, `RecordError`, `TraceID` helpers.
- `Endpoint` accepts URLs (`https://collector:4318`).
- Resource carries `service.instance.id`, host attributes and `deployment.environment.name` (from `Environment`).
- `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_*`).
- `Config.HTTP`, `Config.HTTPClient`, `Config.GRPC` configure the Observer's instrumentation; `HTTPClientConfig.HostFunc` bounds the `host` label.
- `OTEL_EXPORTER_OTLP_PROTOCOL` / `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` select the protocol when `TracerConfig.Protocol` is empty.
- Admin pprof is opt-in (`AdminConfig.EnablePprof`, `OBSX_ADMIN_ENABLE_PPROF`).
- Health reports are cached for one second and hung checks are not restarted; client spans omit the URL query string; abandoned client gRPC streams are recorded as `Canceled`.
- `deploy/` — Grafana dashboard and Prometheus alerts; `examples/service`.
- Metrics: idempotent registration, `Sub`, `GaugeFunc`, `CounterFunc`, `RegisterDBStats`, OpenMetrics handler with trace exemplars.
### Deprecated
- `HTTPMiddleware` → `NewHTTPMiddleware` / `Observer.HTTPMiddleware`. It keeps working with its v1.0.0 metric names (`<ns>_http_requests_total`, `<ns>_http_request_duration_seconds`).
- `HTTPTransport` → `NewHTTPTransport`; `LogHandler` → `NewTraceHandler`. Both now delegate to the new implementations.
### Changed
- `HTTPTransport` client spans carry `server.address` without the port and add `url.full` (credentials stripped).
- Without `Endpoint` and `OTEL_EXPORTER_OTLP_*ENDPOINT`, spans are created and propagated but not exported (previously the exporter tried `localhost:4317`).
## v1.0.0
The API is stable from this release on (semantic versioning).
### Added
- `HTTPMiddleware` — server spans with trace continuation plus `http_requests_total` and `http_request_duration_seconds` metrics.
- `HTTPTransport` — client spans and trace context propagation for outgoing requests.
- `LogHandler` — `slog.Handler` wrapper adding `trace_id` / `span_id` to records.
- `TracerConfig.Insecure`, `TracerConfig.Headers`, `TracerConfig.Attributes`.
- `SetupTracer` installs W3C TraceContext + Baggage propagators and honours `OTEL_EXPORTER_OTLP_*` / `OTEL_RESOURCE_ATTRIBUTES`.
### Changed (breaking since v0.2.0)
- **OTLP connection uses TLS by default.** Set `TracerConfig.Insecure: true` for plaintext collectors — previously the connection was always insecure.
- Sampling is parent-based: `Sampler` applies to root traces, child spans follow the parent's decision.
- `StartSpan` instrumentation scope is `git.codelab.vc/pkg/obsx` (was `obsx`).
+21 -19
View File
@@ -8,35 +8,37 @@ go test ./... # all tests
go test -race ./... # tests with race detector go test -race ./... # tests with race detector
go test -v -run TestName ./... # single test go test -v -run TestName ./... # single test
go vet ./... # static analysis go vet ./... # static analysis
go run ./examples/service # example service (:8080, admin :9090)
``` ```
## Architecture ## Architecture
- **Module**: `git.codelab.vc/pkg/obsx`, Go 1.25.7, depends on OpenTelemetry and Prometheus client_golang - **Module**: `git.codelab.vc/pkg/obsx`, Go 1.26, depends on OpenTelemetry, Prometheus client_golang and gRPC-Go
- **Single package** `obsx` - **Single package** `obsx` (+ `examples/service`, `deploy/` with Grafana dashboard and Prometheus alerts)
### Core patterns ### Core patterns
- **SetupTracer** — creates OTLP gRPC exporter, builds `sdktrace.TracerProvider` with batcher and ratio sampler, sets it as global `otel.TracerProvider` - **New / Observer** — one call wires logger, tracer provider, metrics, health and optional admin server; `Shutdown` flushes spans and stops the admin server
- **StartSpan** — convenience function using `otel.Tracer("obsx")` to start spans via the global provider - **Config** — service identity + per-component configs; `defaults()` fills service name/version and propagates identity to `Tracing`; `WithEnv()` applies `OBSX_*` / `OTEL_*` overrides
- **TracerConfig** — service name, version, OTLP endpoint, sampling ratio; `defaults()` sets `Sampler` to 1.0 if unset - **NewLogger / TraceHandler** — slog JSON/text logger; `TraceHandler` adds `trace_id`/`span_id` from context
- **Metrics** — factory that creates Prometheus `CounterVec`, `HistogramVec`, `GaugeVec` with consistent namespace/subsystem - **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
- **NewMetrics** — creates an isolated `prometheus.Registry` pre-loaded with process and Go collectors - **HTTPMiddleware / HTTPTransport / LogHandler** — the v1.0.0 API (`http.go`, `log.go`), deprecated but must keep working: `HTTPTransport` and `LogHandler` delegate to the new implementations, `HTTPMiddleware` keeps its own metrics `http_requests_total` / `http_request_duration_seconds` under the namespace
- **Handler()** — returns `promhttp.HandlerFor` using the isolated registry - **StartSpan / Trace / RecordError / TraceID** — span helpers on the global provider
- **Registry()** — exposes the underlying `*prometheus.Registry` for direct access - **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
### Tracer lifecycle - **Health** — liveness/readiness checks with timeouts, HTTP handlers, `grpc.health.v1` server, `SetReady`
- **AdminHandler** — `/metrics`, `/healthz`, `/livez`, `/readyz`, `/buildinfo`, `/loglevel`, `/debug/pprof/` (opt-in via `Admin.EnablePprof`)
- `SetupTracer` returns `shutdown func(context.Context) error` — must be called to flush pending spans
- Shutdown is the `TracerProvider.Shutdown` method directly
## Conventions ## Conventions
- Struct-based configs (`TracerConfig`, `MetricsConfig`) with `defaults()` methods - Struct-based configs with `defaults()` methods; no functional options
- Isolated Prometheus registry — not the global default, avoids conflicts in tests and multi-tenant setups - Public API is stable since v1.0.0 — no breaking changes; record changes in `CHANGELOG.md`
- `nil` buckets in `Histogram()` defaults to `prometheus.DefBuckets` - 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
- No functional options — direct struct configuration only - 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 ## See also
- `AGENTS.md` — universal AI agent guide with package map and common tasks - `AGENTS.md` — package map, common tasks, gotchas
+183 -64
View File
@@ -1,6 +1,6 @@
# obsx # 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 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 go get git.codelab.vc/pkg/obsx
@@ -9,86 +9,205 @@ go get git.codelab.vc/pkg/obsx
## Quick start ## Quick start
```go ```go
// Tracing func main() {
shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
ServiceName: "my-service", defer stop()
ServiceVersion: "1.0.0",
Endpoint: "localhost:4317", o, err := obsx.New(ctx, obsx.Config{
Sampler: 1.0, // sample everything ServiceName: "orders",
}) ServiceVersion: "1.4.0",
if err != nil { Environment: "production",
log.Fatal(err) 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",
})
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())
``` ```
## Components A runnable version lives in [`examples/service`](examples/service/main.go).
| Component | What it does | ## What you get
|-----------|-------------|
| `SetupTracer` | Initializes an OpenTelemetry tracer provider with OTLP gRPC exporter, sets it as the global provider. |
| `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. |
| `MetricsConfig` | Configures the metrics factory: namespace and subsystem. |
## Tracing | 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` and, with `Admin.EnablePprof`, `/debug/pprof/`. No authentication: bind it to an internal address. |
`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. | 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 ```go
shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{ obsx.Config{
ServiceName: "orders-api", HTTP: obsx.HTTPServerConfig{
Endpoint: "jaeger:4317", RouteFunc: func(r *http.Request) string {
Sampler: 0.1, // sample 10% return chi.RouteContext(r.Context()).RoutePattern()
}) },
defer shutdown(ctx) // Long-lived connections would distort latency histograms and alerts.
Skip: func(r *http.Request) bool { return r.URL.Path == "/ws" },
},
}
``` ```
Start spans with the convenience helper: ## 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` | `OTEL_EXPORTER_OTLP_PROTOCOL`, then `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 |
| `Admin.EnablePprof` | `false` |
| `HTTP`, `HTTPClient`, `GRPC` | instrumentation settings used by the Observer: `RouteFunc`, `Skip`, `Buckets`, `Propagator`, `HostFunc` |
`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_ENABLE_PPROF` | `Admin.Addr`, `Admin.EnablePprof` |
| `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 ```go
ctx, span := obsx.StartSpan(ctx, "process-order") logger, levelVar := obsx.NewLogger(obsx.LogConfig{Level: "debug"})
defer span.End() 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()...)
``` ```
## Metrics `obsx.NewTraceHandler(h)` adds trace correlation to any existing `slog.Handler`.
`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. 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 (`<ns>_http_requests_total`, `<ns>_http_request_duration_seconds`). The API is stable since v1.0.0 — see [CHANGELOG.md](CHANGELOG.md).
```go ## Behavior notes
m := obsx.NewMetrics(obsx.MetricsConfig{Namespace: "myapp", Subsystem: "db"})
// Counter - `New` installs the global `slog` logger, tracer provider and propagator; `SetupTracer` installs the tracer provider and propagator.
queries := m.Counter("queries_total", "Total queries executed", "operation") - Panics in HTTP/gRPC handlers and `Track` are recorded (500 / `Internal`, failed span) and re-raised.
queries.WithLabelValues("select").Inc() - 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.
// Histogram (nil buckets = prometheus.DefBuckets) - HTTP client latency is measured until response headers arrive.
latency := m.Histogram("query_duration_seconds", "Query latency", nil, "operation") - Client spans record the URL without credentials and without the query string. The `host` label is the URL host; when hosts come from users set `HTTPClient.HostFunc` to keep cardinality bounded.
- Sampling follows the caller's trace headers. On endpoints reachable by untrusted clients set `HTTP.Propagator` / `GRPC.Propagator` to `propagation.NewCompositeTextMapPropagator()` so they cannot force sampling.
// Gauge - Health results are reused for up to one second; a check that outlives its timeout is not started again until it returns.
conns := m.Gauge("connections_active", "Active connections", "pool") - `GaugeFunc`, `CounterFunc` and `RegisterDBStats` panic on a duplicate name instead of silently keeping the first function or pool.
- A panic after a partial HTTP response is counted as 500.
// HTTP handler for /metrics endpoint
http.Handle("/metrics", m.Handler())
```
Access the underlying registry directly:
```go
registry := m.Registry()
```
## Requirements ## 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), [gRPC-Go](https://github.com/grpc/grpc-go).
+80
View File
@@ -0,0 +1,80 @@
package obsx
import (
"io"
"log/slog"
"net/http"
"net/http/pprof"
"strings"
)
// AdminHandler returns the handler served by the admin server:
//
// GET /metrics Prometheus metrics
// GET /healthz, /livez liveness checks
// GET /readyz readiness checks
// GET /buildinfo service name, version, revision, uptime
// GET /loglevel current log level
// PUT /loglevel change log level: body or ?level= "debug", "info", ...
// /debug/pprof/ Go profiling (only with Admin.EnablePprof)
//
// The handler has no authentication: expose it on an internal address only.
func (o *Observer) AdminHandler() http.Handler {
mux := http.NewServeMux()
mux.Handle("GET /metrics", o.metrics.Handler())
mux.Handle("GET /healthz", o.health.LivenessHandler())
mux.Handle("GET /livez", o.health.LivenessHandler())
mux.Handle("GET /readyz", o.health.ReadinessHandler())
mux.HandleFunc("GET /buildinfo", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, o.BuildInfo())
})
mux.Handle("/loglevel", LogLevelHandler(o.level, o.logger))
if o.cfg.Admin.EnablePprof {
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
}
return mux
}
// LogLevelHandler serves the level held by lv: GET returns it, PUT or POST
// changes it from the "level" query parameter or the request body.
// Changes are logged with logger when it is non-nil.
func LogLevelHandler(lv *slog.LevelVar, logger *slog.Logger) http.Handler {
type response struct {
Level string `json:"level"`
Error string `json:"error,omitempty"`
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet, http.MethodHead:
writeJSON(w, http.StatusOK, response{Level: lv.Level().String()})
case http.MethodPut, http.MethodPost:
value := r.URL.Query().Get("level")
if value == "" {
body, _ := io.ReadAll(io.LimitReader(r.Body, 64))
value = strings.TrimSpace(string(body))
}
level, err := ParseLevel(value)
if err != nil {
writeJSON(w, http.StatusBadRequest, response{Level: lv.Level().String(), Error: err.Error()})
return
}
prev := lv.Level()
lv.Set(level)
if logger != nil {
logger.LogAttrs(r.Context(), slog.LevelInfo, "log level changed",
slog.String("from", prev.String()), slog.String("to", level.String()))
}
writeJSON(w, http.StatusOK, response{Level: level.String()})
default:
w.Header().Set("Allow", "GET, HEAD, PUT, POST")
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
}
})
}
+184
View File
@@ -1 +1,185 @@
package obsx package obsx
import (
"os"
"path/filepath"
"runtime"
"runtime/debug"
"strconv"
"strings"
"time"
)
// Config configures an Observer: logging, tracing, metrics, health checks and
// the admin HTTP server, all sharing the same service identity.
type Config struct {
ServiceName string // default: executable name
ServiceVersion string // default: main module version from build info
Environment string // e.g. "production", "staging"
Logging LogConfig
Tracing TracerConfig // ServiceName, ServiceVersion and Environment are inherited when empty
Metrics MetricsConfig
Health HealthConfig // Metrics is set automatically
Admin AdminConfig
// HTTP, HTTPClient and GRPC tune the instrumentation created by the
// Observer (RouteFunc, Skip, Buckets, Propagator, HostFunc...). Metrics,
// Logger and TracerProvider default to the Observer's own.
HTTP HTTPServerConfig
HTTPClient HTTPClientConfig
GRPC GRPCConfig
// DisableAccessLog turns off per-request logs from the HTTP and gRPC
// server instrumentation.
DisableAccessLog bool
}
// AdminConfig configures the internal admin HTTP server exposing /metrics,
// /healthz, /readyz, /buildinfo, /loglevel and, when enabled, /debug/pprof/.
// The server has no authentication: bind it to an internal address.
type AdminConfig struct {
// Addr to listen on, e.g. ":9090". When empty no server is started; mount
// Observer.AdminHandler on your own server instead.
Addr string
// EnablePprof serves /debug/pprof/. Off by default: profiling is costly
// and the admin server is unauthenticated.
EnablePprof bool
}
func (c *Config) defaults() {
if c.ServiceName == "" {
c.ServiceName = filepath.Base(os.Args[0])
}
if c.ServiceVersion == "" {
c.ServiceVersion = buildVersion()
}
if c.Tracing.ServiceName == "" {
c.Tracing.ServiceName = c.ServiceName
}
if c.Tracing.ServiceVersion == "" {
c.Tracing.ServiceVersion = c.ServiceVersion
}
if c.Tracing.Environment == "" {
c.Tracing.Environment = c.Environment
}
c.Logging.defaults()
}
// WithEnv returns a copy of c with fields overridden by environment variables,
// so that deployments can tune observability without code changes:
//
// OBSX_SERVICE_NAME, OTEL_SERVICE_NAME ServiceName
// OBSX_SERVICE_VERSION ServiceVersion
// OBSX_ENVIRONMENT Environment
// OBSX_LOG_LEVEL Logging.Level
// 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
// OBSX_HEALTH_TIMEOUT Health.Timeout (Go duration, e.g. "3s")
// OBSX_ADMIN_ADDR Admin.Addr
// OBSX_ADMIN_ENABLE_PPROF Admin.EnablePprof
// OBSX_DISABLE_ACCESS_LOG DisableAccessLog
//
// Standard OTEL_EXPORTER_OTLP_* and OTEL_RESOURCE_ATTRIBUTES variables are
// honored by the trace exporter independently of WithEnv.
// Malformed numeric, boolean and duration values are ignored.
func (c Config) WithEnv() Config {
envString(&c.ServiceName, "OTEL_SERVICE_NAME")
envString(&c.ServiceName, "OBSX_SERVICE_NAME")
envString(&c.ServiceVersion, "OBSX_SERVICE_VERSION")
envString(&c.Environment, "OBSX_ENVIRONMENT")
envString(&c.Logging.Level, "OBSX_LOG_LEVEL")
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")
envString(&c.Metrics.Namespace, "OBSX_METRICS_NAMESPACE")
envDuration(&c.Health.Timeout, "OBSX_HEALTH_TIMEOUT")
envString(&c.Admin.Addr, "OBSX_ADMIN_ADDR")
envBool(&c.Admin.EnablePprof, "OBSX_ADMIN_ENABLE_PPROF")
envBool(&c.DisableAccessLog, "OBSX_DISABLE_ACCESS_LOG")
return c
}
func envString(dst *string, key string) {
if v, ok := os.LookupEnv(key); ok && v != "" {
*dst = v
}
}
func envBool(dst *bool, key string) {
if v, err := strconv.ParseBool(os.Getenv(key)); err == nil {
*dst = v
}
}
func envFloat(dst *float64, key string) {
if v, err := strconv.ParseFloat(os.Getenv(key), 64); err == nil {
*dst = v
}
}
func envDuration(dst *time.Duration, key string) {
if v, err := time.ParseDuration(os.Getenv(key)); err == nil {
*dst = v
}
}
// BuildInfo describes the running binary.
type BuildInfo struct {
Service string `json:"service"`
Version string `json:"version"`
Environment string `json:"environment,omitempty"`
Revision string `json:"revision,omitempty"`
GoVersion string `json:"go_version"`
StartTime time.Time `json:"start_time"`
Uptime string `json:"uptime"`
}
func newBuildInfo(cfg Config, start time.Time) BuildInfo {
return BuildInfo{
Service: cfg.ServiceName,
Version: cfg.ServiceVersion,
Environment: cfg.Environment,
Revision: vcsRevision(),
GoVersion: runtime.Version(),
StartTime: start,
}
}
func buildVersion() string {
bi, ok := debug.ReadBuildInfo()
if !ok || bi.Main.Version == "" || bi.Main.Version == "(devel)" {
return ""
}
return bi.Main.Version
}
func vcsRevision() string {
bi, ok := debug.ReadBuildInfo()
if !ok {
return ""
}
var rev string
var dirty bool
for _, s := range bi.Settings {
switch s.Key {
case "vcs.revision":
rev = s.Value
case "vcs.modified":
dirty = s.Value == "true"
}
}
if rev != "" && dirty {
rev += "-dirty"
}
return strings.TrimSpace(rev)
}
File diff suppressed because it is too large. Load diff
+115
View File
@@ -0,0 +1,115 @@
# Prometheus alerting rules for services instrumented with obsx.
#
# Built-in obsx metrics have identical names in every service, so these rules
# work for all of them; alerts are grouped by the scrape "job" label.
# Thresholds are reasonable defaults: tune them per environment.
#
# Load with Prometheus `rule_files`, or wrap into a PrometheusRule resource
# (spec.groups = the groups below) for the Prometheus Operator.
groups:
- name: obsx-service
rules:
- alert: ServiceRestartingFrequently
expr: changes(process_start_time_seconds{job!=""}[15m]) > 2
for: 0m
labels:
severity: warning
annotations:
summary: "{{ $labels.job }} ({{ $labels.instance }}) restarted {{ $value }} times in 15m"
- alert: HealthCheckFailing
expr: health_check_status == 0
for: 5m
labels:
severity: warning
annotations:
summary: "{{ $labels.job }}: {{ $labels.kind }} check {{ $labels.check }} is failing"
description: "Inspect /readyz or /healthz on the admin port of {{ $labels.instance }}."
- name: obsx-http
rules:
- alert: HTTPServerHighErrorRate
expr: |
sum by (job) (rate(http_server_requests_total{code=~"5.."}[5m]))
/
sum by (job) (rate(http_server_requests_total[5m]))
> 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "{{ $labels.job }}: {{ $value | humanizePercentage }} of HTTP requests fail with 5xx"
- alert: HTTPServerHighLatency
expr: |
histogram_quantile(0.99,
sum by (job, le) (rate(http_server_request_duration_seconds_bucket{route!="unmatched"}[5m]))
) > 1
for: 10m
labels:
severity: warning
annotations:
summary: "{{ $labels.job }}: HTTP p99 latency is {{ $value | humanizeDuration }}"
- alert: HTTPClientHighErrorRate
expr: |
sum by (job, host) (rate(http_client_requests_total{code=~"5..|error"}[5m]))
/
sum by (job, host) (rate(http_client_requests_total[5m]))
> 0.1
for: 5m
labels:
severity: warning
annotations:
summary: "{{ $labels.job }}: {{ $value | humanizePercentage }} of calls to {{ $labels.host }} fail"
- name: obsx-grpc
rules:
- alert: GRPCServerHighErrorRate
expr: |
sum by (job) (rate(grpc_server_requests_total{code=~"Unknown|DeadlineExceeded|Unimplemented|Internal|Unavailable|DataLoss"}[5m]))
/
sum by (job) (rate(grpc_server_requests_total[5m]))
> 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "{{ $labels.job }}: {{ $value | humanizePercentage }} of gRPC calls fail with server errors"
- alert: GRPCServerHighLatency
expr: |
histogram_quantile(0.99,
sum by (job, le) (rate(grpc_server_request_duration_seconds_bucket[5m]))
) > 1
for: 10m
labels:
severity: warning
annotations:
summary: "{{ $labels.job }}: gRPC p99 latency is {{ $value | humanizeDuration }}"
- alert: GRPCClientHighErrorRate
expr: |
sum by (job, service) (rate(grpc_client_requests_total{code!~"OK|Canceled|InvalidArgument|NotFound|AlreadyExists|PermissionDenied|Unauthenticated|FailedPrecondition|OutOfRange"}[5m]))
/
sum by (job, service) (rate(grpc_client_requests_total[5m]))
> 0.1
for: 5m
labels:
severity: warning
annotations:
summary: "{{ $labels.job }}: {{ $value | humanizePercentage }} of calls to {{ $labels.service }} fail"
- name: obsx-operations
rules:
- alert: OperationHighErrorRate
expr: |
sum by (job, operation) (rate(operation_duration_seconds_count{status="error"}[5m]))
/
sum by (job, operation) (rate(operation_duration_seconds_count[5m]))
> 0.1
for: 10m
labels:
severity: warning
annotations:
summary: "{{ $labels.job }}: operation {{ $labels.operation }} fails {{ $value | humanizePercentage }} of the time"
+59 -12
View File
@@ -1,17 +1,64 @@
// Package obsx provides observability setup for the platform: metrics (Prometheus) // Package obsx is an observability toolkit for Go microservices: structured
// and tracing (OpenTelemetry). // 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 // # Quick Start
// //
// // Tracing // o, err := obsx.New(ctx, obsx.Config{
// shutdown, err := obsx.SetupTracer(ctx, obsx.TracerConfig{ // ServiceName: "orders",
// ServiceName: "my-service", // ServiceVersion: "1.4.0",
// Endpoint: "localhost:4317", // Environment: "production",
// }) // Tracing: obsx.TracerConfig{Endpoint: "otel-collector:4317", Insecure: true},
// defer shutdown(ctx) // Admin: obsx.AdminConfig{Addr: ":9090"}, // /metrics, /healthz, /readyz
// }.WithEnv())
// if err != nil {
// log.Fatal(err)
// }
// defer o.Shutdown(context.Background())
// //
// // Metrics // o.Health().AddReadinessCheck("postgres", db.PingContext)
// metrics := obsx.NewMetrics(obsx.MetricsConfig{Namespace: "myapp"}) //
// reqCounter := metrics.Counter("requests_total", "Total requests", "method", "status") // http.ListenAndServe(":8080", o.HTTPMiddleware(mux)) // HTTP server
// http.Handle("/metrics", metrics.Handler()) // 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 { ... })
//
// # 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 v1.0.0
// helpers HTTPMiddleware, HTTPTransport and LogHandler still work but are
// deprecated in favour of NewHTTPMiddleware, NewHTTPTransport and
// NewTraceHandler.
package obsx package obsx
+142
View File
@@ -0,0 +1,142 @@
package obsx_test
import (
"context"
"database/sql"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"git.codelab.vc/pkg/obsx"
"google.golang.org/grpc"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)
// A complete HTTP service: one call to New wires logging, tracing, metrics,
// health checks and the admin server; instrumentation is a single wrapper.
func Example() {
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())
if err != nil {
log.Fatal(err)
}
defer o.Shutdown(context.Background())
var db *sql.DB // your database
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, "SELECT 1").Err()
})
if err != nil {
slog.ErrorContext(r.Context(), "get order failed", "error", err) // has trace_id
http.Error(w, "internal error", http.StatusInternalServerError)
}
})
srv := &http.Server{Addr: ":8080", Handler: o.HTTPMiddleware(mux)}
go func() { _ = srv.ListenAndServe() }()
<-ctx.Done()
o.Health().SetReady(false) // stop receiving traffic
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = srv.Shutdown(shutdownCtx)
}
// gRPC servers and clients are instrumented with ready-made options.
func Example_grpc() {
o, err := obsx.New(context.Background(), obsx.Config{ServiceName: "billing"})
if err != nil {
log.Fatal(err)
}
defer o.Shutdown(context.Background())
srv := grpc.NewServer(o.GRPCServerOptions()...)
healthpb.RegisterHealthServer(srv, o.Health().GRPCServer())
conn, err := grpc.NewClient("payments:9000", o.GRPCDialOptions()...) // + transport credentials
if err == nil {
defer conn.Close()
}
}
// Outgoing HTTP calls propagate the trace and are measured per host.
func ExampleObserver_HTTPClient() {
o, _ := obsx.New(context.Background(), obsx.Config{ServiceName: "gateway"})
defer o.Shutdown(context.Background())
client := o.HTTPClient()
client.Timeout = 5 * time.Second
req, _ := http.NewRequestWithContext(context.Background(), "GET", "http://users/api/v1/me", nil)
if resp, err := client.Do(req); err == nil {
resp.Body.Close()
}
}
// Business metrics share the service registry and are exposed on /metrics.
func ExampleMetrics() {
m := obsx.NewMetrics(obsx.MetricsConfig{Namespace: "shop"})
orders := m.Counter("orders_created_total", "Orders created.", "payment_method")
orders.WithLabelValues("card").Inc()
cart := m.Sub("cart").Histogram("items", "Items per cart.", []float64{1, 2, 5, 10, 20})
cart.WithLabelValues().Observe(3)
queue := make(chan struct{}, 100)
m.GaugeFunc("queue_depth", "Pending jobs.", func() float64 { return float64(len(queue)) })
http.Handle("/metrics", m.Handler())
}
// Health checks run concurrently with a per-check timeout.
func ExampleHealth() {
h := obsx.NewHealth(obsx.HealthConfig{Timeout: 2 * time.Second})
h.AddReadinessCheck("cache", func(ctx context.Context) error { return nil })
report := h.CheckReadiness(context.Background())
fmt.Println(report.Status, report.Checks["cache"].Status)
// Output: ok ok
}
// Components can be used standalone without an Observer.
func ExampleNewHTTPMiddleware() {
m := obsx.NewMetrics(obsx.MetricsConfig{})
logger, _ := obsx.NewLogger(obsx.LogConfig{Level: "info"})
mw := obsx.NewHTTPMiddleware(obsx.HTTPServerConfig{
Metrics: m,
Logger: logger,
TraceIDHeader: "X-Trace-Id",
})
mux := http.NewServeMux()
mux.HandleFunc("GET /ping", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("pong")) })
_ = http.ListenAndServe(":8080", mw(mux))
}
// Trace wraps a unit of work in a span and records its error.
func ExampleTrace() {
err := obsx.Trace(context.Background(), "reconcile", func(ctx context.Context) error {
slog.InfoContext(ctx, "reconciling", "trace_id", obsx.TraceID(ctx))
return nil
})
_ = err
}
+90
View File
@@ -0,0 +1,90 @@
// Command service is a minimal microservice instrumented with obsx.
//
// go run ./examples/service
// curl localhost:8080/hello/world
// curl localhost:9090/metrics
// curl localhost:9090/readyz
//
// Set OBSX_TRACING_ENDPOINT=localhost:4317 to export traces to a collector.
package main
import (
"context"
"errors"
"log/slog"
"math/rand/v2"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"git.codelab.vc/pkg/obsx"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
o, err := obsx.New(ctx, obsx.Config{
ServiceName: "greeter",
ServiceVersion: "0.1.0",
Environment: "dev",
Admin: obsx.AdminConfig{Addr: ":9090"},
}.WithEnv())
if err != nil {
slog.Error("observability setup failed", "error", err)
os.Exit(1)
}
defer func() {
if err := o.Shutdown(context.Background()); err != nil {
slog.Error("observability shutdown failed", "error", err)
}
}()
// Business metric under the service namespace.
greetings := o.Metrics().Counter("greetings_total", "Greetings sent.", "lang")
o.Health().AddReadinessCheck("storage", func(ctx context.Context) error {
return nil // e.g. db.PingContext(ctx)
})
mux := http.NewServeMux()
mux.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
err := o.Track(r.Context(), "storage.load_template", func(ctx context.Context) error {
time.Sleep(time.Duration(rand.IntN(20)) * time.Millisecond)
if rand.IntN(10) == 0 {
return errors.New("template cache miss")
}
return nil
})
if err != nil {
slog.WarnContext(r.Context(), "falling back to default template", "error", err)
}
greetings.WithLabelValues("en").Inc()
_, _ = w.Write([]byte("hello, " + r.PathValue("name") + "\n"))
})
srv := &http.Server{
Addr: ":8080",
Handler: o.HTTPMiddleware(mux),
ReadHeaderTimeout: 5 * time.Second,
}
go func() {
slog.Info("http server started", "addr", srv.Addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("http server failed", "error", err)
stop()
}
}()
<-ctx.Done()
slog.Info("shutting down")
o.Health().SetReady(false)
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("http server shutdown failed", "error", err)
}
}
+106
View File
@@ -0,0 +1,106 @@
package obsx
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"net"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"go.opentelemetry.io/otel"
coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
type collector struct {
coltracepb.UnimplementedTraceServiceServer
got chan *coltracepb.ExportTraceServiceRequest
}
func (c *collector) Export(_ context.Context, r *coltracepb.ExportTraceServiceRequest) (*coltracepb.ExportTraceServiceResponse, error) {
c.got <- r
return &coltracepb.ExportTraceServiceResponse{}, nil
}
// End to end: spans reach a real OTLP gRPC collector, over plaintext, TLS
// with the standard certificate variable, and TLS with TracerConfig.TLS.
func TestSetupTracer_Exports(t *testing.T) {
for _, name := range []string{"insecure", "tls", "custom-tls"} {
insecure := name == "insecure"
t.Run(name, func(t *testing.T) {
var tlsCfg *tls.Config
prev := otel.GetTracerProvider()
t.Cleanup(func() { otel.SetTracerProvider(prev) })
var opts []grpc.ServerOption
if !insecure {
// Borrow httptest's self-signed certificate (valid for 127.0.0.1).
ts := httptest.NewTLSServer(nil)
defer ts.Close()
opts = append(opts, grpc.Creds(credentials.NewServerTLSFromCert(&ts.TLS.Certificates[0])))
if name == "custom-tls" {
pool := x509.NewCertPool()
pool.AddCert(ts.Certificate())
tlsCfg = &tls.Config{RootCAs: pool}
} else {
ca := filepath.Join(t.TempDir(), "ca.pem")
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ts.Certificate().Raw})
if err := os.WriteFile(ca, pemBytes, 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("OTEL_EXPORTER_OTLP_CERTIFICATE", ca)
}
}
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
c := &collector{got: make(chan *coltracepb.ExportTraceServiceRequest, 1)}
srv := grpc.NewServer(opts...)
coltracepb.RegisterTraceServiceServer(srv, c)
go srv.Serve(lis)
defer srv.Stop()
ctx := context.Background()
shutdown, err := SetupTracer(ctx, TracerConfig{
ServiceName: "export-test",
Endpoint: lis.Addr().String(),
Insecure: insecure,
TLS: tlsCfg,
})
if err != nil {
t.Fatal(err)
}
_, span := StartSpan(ctx, "exported")
span.End()
if err := shutdown(ctx); err != nil { // flushes
t.Fatalf("shutdown: %v", err)
}
select {
case r := <-c.got:
rs := r.ResourceSpans[0]
if n := rs.ScopeSpans[0].Spans[0].Name; n != "exported" {
t.Errorf("span name = %q", n)
}
var svc string
for _, a := range rs.Resource.Attributes {
if a.Key == "service.name" {
svc = a.Value.GetStringValue()
}
}
if svc != "export-test" {
t.Errorf("service.name = %q", svc)
}
default:
t.Fatal("collector received no spans")
}
})
}
}
+26 -23
View File
@@ -1,36 +1,39 @@
module git.codelab.vc/pkg/obsx module git.codelab.vc/pkg/obsx
go 1.25.7 go 1.26.0
require ( require (
github.com/prometheus/client_golang v1.22.0 github.com/prometheus/client_golang v1.25.0
go.opentelemetry.io/otel v1.35.0 go.opentelemetry.io/otel v1.47.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0
go.opentelemetry.io/otel/sdk v1.35.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0
go.opentelemetry.io/otel/trace v1.35.0 go.opentelemetry.io/otel/sdk v1.47.0
go.opentelemetry.io/otel/trace v1.47.0
go.opentelemetry.io/proto/otlp v1.11.1
google.golang.org/grpc v1.85.0
) )
require ( require (
github.com/beorn7/perks v1.0.1 // indirect github.com/beorn7/perks v1.0.1 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/prometheus/client_model v0.6.1 // indirect github.com/pandatix/go-abnf v0.5.5 // indirect
github.com/prometheus/common v0.62.0 // indirect github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/procfs v0.15.1 // indirect github.com/prometheus/common v0.73.1 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect github.com/prometheus/procfs v0.23.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel/metric v1.35.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.5.0 // indirect go.opentelemetry.io/otel/log v1.47.0 // indirect
golang.org/x/net v0.35.0 // indirect go.opentelemetry.io/otel/metric v1.47.0 // indirect
golang.org/x/sys v0.30.0 // indirect golang.org/x/net v0.62.0 // indirect
golang.org/x/text v0.22.0 // indirect golang.org/x/sys v0.50.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a // indirect golang.org/x/text v0.44.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a // indirect google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c // indirect
google.golang.org/grpc v1.71.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect
google.golang.org/protobuf v1.36.5 // indirect google.golang.org/protobuf v1.36.12 // indirect
) )
+62 -56
View File
@@ -1,14 +1,12 @@
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
@@ -17,59 +15,67 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1 h1:e9Rjr40Z98/clHv5Yg79Is0NtosR5LXRvdr7o/6NwbA= github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 h1:5T5Ns3kMpWr+z3s5ZA0e7ljVyWNVNxK76sHPAxi5D1k=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1/go.mod h1:tIxuGz/9mpox++sgp9fJjHO0+q1X9/UOWd798aAm22M= github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0/go.mod h1:oWNYw09cH8wl8fFgC5hKlBLxR4XfKy2KQpP8MJjeCcc=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= github.com/prometheus/common v0.73.1 h1:SZWh/j4AvhCdhX8jvYSnxvPxhWlC9QZkjJ+tOrEr7kU=
github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= github.com/prometheus/common v0.73.1/go.mod h1:I9aA/Ukz9s1olOobh8KtCkU7B1mQPQsB9UvQPsUQ1Dk=
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 h1:1fTNlAIJZGWLP5FVu0fikVry1IsiUnXjf7QFvoNN3Xw= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0/go.mod h1:zjPK58DtkqQFn+YUMbx0M2XV3QgKU0gS9LeGohREyK4= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0 h1:m639+BofXTvcY1q8CGs4ItwQarYtJPOWmVobfM1HpVI= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 h1:UFpxOpYPmMNUtOWhdb+nC1WELIgVf8z9higURrbzYU4=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0/go.mod h1:LjReUci/F4BUyv+y4dwnq3h/26iNOeC3wAIqgvTIZVo= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0/go.mod h1:YBGjxe3lt0jtXoEXxGrGhv/jM7oUBUDVK7zhAvNyEjc=
go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY= go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg= go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
go.opentelemetry.io/proto/otlp v1.5.0 h1:xJvq7gMzB31/d406fB8U5CBdyQGw4P399D1aQWU/3i4= go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWp0eVQ4yIXvJ4= go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a h1:nwKuGPlUAt+aR+pcrkfFRrTU1BVrSmYyYMxYbUIVHr0= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a/go.mod h1:3kWAYMk1I75K4vykHtKt2ycnOgpA6974V7bREqbsenU= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a h1:51aaUVRocpvUOSQKM6Q7VuoaktNIaMCLuhZB6DKksq4= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a/go.mod h1:uRxBH1mhmO8PGhU89cMcHaXKZqO+OfakD8QQO0oYwlQ= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c h1:ofk4SEqvpf6M5VWh88xRp42IYgdVOh7gffebnDj3OqU=
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c/go.mod h1:OzYcNQzaMRKcOFRMtyLzG/cfW1SmS2eh+7UmOLLFblk=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c h1:XXChExL+Tm7Ubp0x0VXUEncPLHrkXIgoVWqnxmKNbAA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+393
View File
@@ -0,0 +1,393 @@
package obsx
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
otelcodes "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
// GRPCConfig configures gRPC server and client instrumentation.
type GRPCConfig struct {
Metrics *Metrics // nil disables metrics
Logger *slog.Logger // nil disables server access logs
TracerProvider trace.TracerProvider // nil: global provider
Propagator propagation.TextMapPropagator // nil: global propagator
Buckets []float64 // latency buckets in seconds, default: prometheus.DefBuckets
// Skip excludes methods from instrumentation by full name, e.g.
// "/grpc.health.v1.Health/Check".
Skip func(fullMethod string) bool
}
func (c *GRPCConfig) defaults() {
if c.TracerProvider == nil {
c.TracerProvider = otel.GetTracerProvider()
}
if c.Propagator == nil {
c.Propagator = otel.GetTextMapPropagator()
}
}
// GRPCInterceptors bundles instrumented gRPC interceptors.
//
// Server metrics: grpc_server_requests_total, grpc_server_request_duration_seconds
// (labels service, method, code) and grpc_server_requests_in_flight.
// Client metrics: grpc_client_requests_total, grpc_client_request_duration_seconds
// (labels service, method, code).
type GRPCInterceptors struct {
UnaryServer grpc.UnaryServerInterceptor
StreamServer grpc.StreamServerInterceptor
UnaryClient grpc.UnaryClientInterceptor
StreamClient grpc.StreamClientInterceptor
}
// NewGRPCInterceptors creates server and client interceptors providing
// tracing with metadata propagation, metrics and server access logs.
func NewGRPCInterceptors(cfg GRPCConfig) *GRPCInterceptors {
cfg.defaults()
g := &grpcInstrumentation{
cfg: cfg,
tracer: cfg.TracerProvider.Tracer(tracerName),
}
if cfg.Metrics != nil {
m := cfg.Metrics.base()
g.serverRequests = m.Counter("grpc_server_requests_total",
"Total number of gRPC calls handled by the server.", "service", "method", "code")
g.serverDuration = m.Histogram("grpc_server_request_duration_seconds",
"Duration of gRPC calls handled by the server.", cfg.Buckets, "service", "method", "code")
g.serverInflight = m.Gauge("grpc_server_requests_in_flight",
"Number of gRPC calls currently being handled by the server.").WithLabelValues()
g.clientRequests = m.Counter("grpc_client_requests_total",
"Total number of outgoing gRPC calls.", "service", "method", "code")
g.clientDuration = m.Histogram("grpc_client_request_duration_seconds",
"Duration of outgoing gRPC calls.", cfg.Buckets, "service", "method", "code")
}
return &GRPCInterceptors{
UnaryServer: g.unaryServer,
StreamServer: g.streamServer,
UnaryClient: g.unaryClient,
StreamClient: g.streamClient,
}
}
// ServerOptions returns grpc.NewServer options installing the server interceptors.
func (i *GRPCInterceptors) ServerOptions() []grpc.ServerOption {
return []grpc.ServerOption{
grpc.ChainUnaryInterceptor(i.UnaryServer),
grpc.ChainStreamInterceptor(i.StreamServer),
}
}
// DialOptions returns grpc.NewClient options installing the client interceptors.
func (i *GRPCInterceptors) DialOptions() []grpc.DialOption {
return []grpc.DialOption{
grpc.WithChainUnaryInterceptor(i.UnaryClient),
grpc.WithChainStreamInterceptor(i.StreamClient),
}
}
type grpcInstrumentation struct {
cfg GRPCConfig
tracer trace.Tracer
serverRequests *prometheus.CounterVec
serverDuration *prometheus.HistogramVec
serverInflight prometheus.Gauge
clientRequests *prometheus.CounterVec
clientDuration *prometheus.HistogramVec
}
func (g *grpcInstrumentation) skip(fullMethod string) bool {
return g.cfg.Skip != nil && g.cfg.Skip(fullMethod)
}
// startServer extracts the remote span context and starts a server span.
func (g *grpcInstrumentation) startServer(ctx context.Context, fullMethod string) (context.Context, trace.Span) {
md, _ := metadata.FromIncomingContext(ctx)
ctx = g.cfg.Propagator.Extract(ctx, metadataCarrier(md))
service, method := splitFullMethod(fullMethod)
attrs := []attribute.KeyValue{
attribute.String("rpc.system", "grpc"),
attribute.String("rpc.service", service),
attribute.String("rpc.method", method),
}
if p, ok := peer.FromContext(ctx); ok && p.Addr != nil {
attrs = append(attrs, attribute.String("client.address", clientIP(p.Addr.String())))
}
ctx, span := g.tracer.Start(ctx, strings.TrimPrefix(fullMethod, "/"),
trace.WithSpanKind(trace.SpanKindServer),
trace.WithAttributes(attrs...),
)
if g.serverInflight != nil {
g.serverInflight.Inc()
}
return ctx, span
}
func (g *grpcInstrumentation) finishServer(ctx context.Context, span trace.Span, fullMethod string, start time.Time, err error) {
defer span.End()
st, _ := status.FromError(err)
code := st.Code()
elapsed := time.Since(start)
service, method := splitFullMethod(fullMethod)
span.SetAttributes(attribute.Int("rpc.grpc.status_code", int(code)))
isServerErr := isServerError(code)
if isServerErr {
span.RecordError(err)
span.SetStatus(otelcodes.Error, st.Message())
}
if g.serverRequests != nil {
g.serverInflight.Dec()
g.serverRequests.WithLabelValues(service, method, code.String()).Inc()
observe(ctx, g.serverDuration.WithLabelValues(service, method, code.String()), elapsed.Seconds())
}
if g.cfg.Logger != nil {
level := slog.LevelInfo
if isServerErr {
level = slog.LevelError
}
attrs := []slog.Attr{
slog.String("service", service),
slog.String("method", method),
slog.String("code", code.String()),
durationAttr(elapsed),
}
if err != nil {
attrs = append(attrs, slog.String("error", st.Message()))
}
g.cfg.Logger.LogAttrs(ctx, level, "grpc request", attrs...)
}
}
// recoverServer converts a handler panic into a recorded error and re-panics.
func (g *grpcInstrumentation) recoverServer(ctx context.Context, span trace.Span, fullMethod string, start time.Time) {
if rec := recover(); rec != nil {
err := status.Error(codes.Internal, fmt.Sprintf("panic: %v", rec))
g.finishServer(ctx, span, fullMethod, start, err)
panic(rec)
}
}
func (g *grpcInstrumentation) unaryServer(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
if g.skip(info.FullMethod) {
return handler(ctx, req)
}
start := time.Now()
ctx, span := g.startServer(ctx, info.FullMethod)
defer g.recoverServer(ctx, span, info.FullMethod, start)
resp, err := handler(ctx, req)
g.finishServer(ctx, span, info.FullMethod, start, err)
return resp, err
}
func (g *grpcInstrumentation) streamServer(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if g.skip(info.FullMethod) {
return handler(srv, ss)
}
start := time.Now()
ctx, span := g.startServer(ss.Context(), info.FullMethod)
defer g.recoverServer(ctx, span, info.FullMethod, start)
err := handler(srv, &serverStream{ServerStream: ss, ctx: ctx})
g.finishServer(ctx, span, info.FullMethod, start, err)
return err
}
// startClient starts a client span and injects its context into outgoing metadata.
func (g *grpcInstrumentation) startClient(ctx context.Context, fullMethod, target string) (context.Context, trace.Span) {
service, method := splitFullMethod(fullMethod)
ctx, span := g.tracer.Start(ctx, strings.TrimPrefix(fullMethod, "/"),
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.String("rpc.system", "grpc"),
attribute.String("rpc.service", service),
attribute.String("rpc.method", method),
attribute.String("server.address", target),
),
)
md, ok := metadata.FromOutgoingContext(ctx)
if ok {
md = md.Copy()
} else {
md = metadata.MD{}
}
g.cfg.Propagator.Inject(ctx, metadataCarrier(md))
return metadata.NewOutgoingContext(ctx, md), span
}
func (g *grpcInstrumentation) finishClient(ctx context.Context, span trace.Span, fullMethod string, start time.Time, err error) {
defer span.End()
st, _ := status.FromError(err)
code := st.Code()
span.SetAttributes(attribute.Int("rpc.grpc.status_code", int(code)))
if code != codes.OK {
span.RecordError(err)
span.SetStatus(otelcodes.Error, st.Message())
}
if g.clientRequests != nil {
service, method := splitFullMethod(fullMethod)
g.clientRequests.WithLabelValues(service, method, code.String()).Inc()
observe(ctx, g.clientDuration.WithLabelValues(service, method, code.String()), time.Since(start).Seconds())
}
}
func (g *grpcInstrumentation) unaryClient(ctx context.Context, fullMethod string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
if g.skip(fullMethod) {
return invoker(ctx, fullMethod, req, reply, cc, opts...)
}
start := time.Now()
ctx, span := g.startClient(ctx, fullMethod, cc.Target())
err := invoker(ctx, fullMethod, req, reply, cc, opts...)
g.finishClient(ctx, span, fullMethod, start, err)
return err
}
func (g *grpcInstrumentation) streamClient(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, fullMethod string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
if g.skip(fullMethod) {
return streamer(ctx, desc, cc, fullMethod, opts...)
}
start := time.Now()
ctx, span := g.startClient(ctx, fullMethod, cc.Target())
cs, err := streamer(ctx, desc, cc, fullMethod, opts...)
if err != nil {
g.finishClient(ctx, span, fullMethod, start, err)
return nil, err
}
s := &clientStream{
ClientStream: cs,
desc: desc,
finish: func(err error) {
g.finishClient(ctx, span, fullMethod, start, err)
},
}
// A caller may cancel and walk away without reading the stream to the end.
s.stop = context.AfterFunc(ctx, func() { s.done(status.FromContextError(ctx.Err()).Err()) })
return s, nil
}
// serverStream overrides the stream context with the traced one.
type serverStream struct {
grpc.ServerStream
ctx context.Context
}
func (s *serverStream) Context() context.Context { return s.ctx }
// clientStream finishes the span and metrics when the stream completes:
// RecvMsg returns io.EOF or an error, or the single response of a
// non-server-streaming call has been received.
type clientStream struct {
grpc.ClientStream
desc *grpc.StreamDesc
once sync.Once
finish func(error)
stop func() bool // unregisters the cancellation watcher
}
func (s *clientStream) done(err error) {
s.once.Do(func() { s.finish(err) })
}
// end finishes the stream from one of its own methods.
func (s *clientStream) end(err error) {
s.stop()
s.done(err)
}
func (s *clientStream) RecvMsg(m any) error {
err := s.ClientStream.RecvMsg(m)
switch {
case errors.Is(err, io.EOF):
s.end(nil)
case err != nil:
s.end(err)
case !s.desc.ServerStreams:
s.end(nil)
}
return err
}
func (s *clientStream) SendMsg(m any) error {
err := s.ClientStream.SendMsg(m)
if err != nil && !errors.Is(err, io.EOF) {
s.end(err)
}
return err
}
func (s *clientStream) Header() (metadata.MD, error) {
md, err := s.ClientStream.Header()
if err != nil {
s.end(err)
}
return md, err
}
// isServerError reports whether code indicates a server-side failure
// (as opposed to a client error such as InvalidArgument or NotFound).
func isServerError(c codes.Code) bool {
switch c {
case codes.Unknown, codes.DeadlineExceeded, codes.Unimplemented,
codes.Internal, codes.Unavailable, codes.DataLoss:
return true
default:
return false
}
}
// splitFullMethod splits "/pkg.Service/Method" into ("pkg.Service", "Method").
func splitFullMethod(fullMethod string) (service, method string) {
name := strings.TrimPrefix(fullMethod, "/")
if i := strings.LastIndexByte(name, '/'); i >= 0 {
return name[:i], name[i+1:]
}
return "unknown", name
}
// metadataCarrier adapts gRPC metadata to propagation.TextMapCarrier.
type metadataCarrier metadata.MD
func (c metadataCarrier) Get(key string) string {
if v := metadata.MD(c).Get(key); len(v) > 0 {
return v[0]
}
return ""
}
func (c metadataCarrier) Set(key, value string) {
metadata.MD(c).Set(key, value)
}
func (c metadataCarrier) Keys() []string {
keys := make([]string, 0, len(c))
for k := range c {
keys = append(keys, k)
}
return keys
}
+180
View File
@@ -0,0 +1,180 @@
package obsx
import (
"bytes"
"context"
"io"
"net"
"strings"
"testing"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
grpccodes "google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
)
// startGRPC serves a grpc.health.v1 service backed by h over an in-memory
// connection, with both server and client instrumented by ic.
func startGRPC(t *testing.T, h *Health, ic *GRPCInterceptors) healthpb.HealthClient {
t.Helper()
return startGRPCServer(t, h.GRPCServer(), ic)
}
func startGRPCServer(t *testing.T, impl healthpb.HealthServer, ic *GRPCInterceptors) healthpb.HealthClient {
t.Helper()
ln := bufconn.Listen(1 << 20)
srv := grpc.NewServer(ic.ServerOptions()...)
healthpb.RegisterHealthServer(srv, impl)
go func() { _ = srv.Serve(ln) }()
t.Cleanup(srv.Stop)
opts := append([]grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return ln.DialContext(ctx) }),
}, ic.DialOptions()...)
conn, err := grpc.NewClient("passthrough:///bufnet", opts...)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
return healthpb.NewHealthClient(conn)
}
func TestGRPC_UnaryInstrumentation(t *testing.T) {
m := NewMetrics(MetricsConfig{})
tp, exp := newTestProvider(t)
var logs bytes.Buffer
logger, _ := NewLogger(LogConfig{Output: &logs})
h := NewHealth(HealthConfig{})
client := startGRPC(t, h, NewGRPCInterceptors(GRPCConfig{
Metrics: m,
Logger: logger,
TracerProvider: tp,
Propagator: testPropagator,
}))
resp, err := client.Check(context.Background(), &healthpb.HealthCheckRequest{})
if err != nil {
t.Fatal(err)
}
if resp.Status != healthpb.HealthCheckResponse_SERVING {
t.Errorf("status = %v, want SERVING", resp.Status)
}
h.SetReady(false)
resp, err = client.Check(context.Background(), &healthpb.HealthCheckRequest{})
if err != nil {
t.Fatal(err)
}
if resp.Status != healthpb.HealthCheckResponse_NOT_SERVING {
t.Errorf("status = %v, want NOT_SERVING", resp.Status)
}
body := scrape(t, m)
for _, want := range []string{
`grpc_server_requests_total{code="OK",method="Check",service="grpc.health.v1.Health"} 2`,
`grpc_client_requests_total{code="OK",method="Check",service="grpc.health.v1.Health"} 2`,
`grpc_server_request_duration_seconds_count{code="OK",method="Check",service="grpc.health.v1.Health"} 2`,
`grpc_server_requests_in_flight 0`,
} {
if !strings.Contains(body, want) {
t.Errorf("metrics missing %q", want)
}
}
// Server span (ended first) must be a child of the client span.
spans := exp.GetSpans()
if len(spans) != 4 {
t.Fatalf("got %d spans, want 4", len(spans))
}
server, client0 := spans[0], spans[1]
if server.SpanKind != trace.SpanKindServer || client0.SpanKind != trace.SpanKindClient {
t.Fatalf("unexpected span kinds: %v, %v", server.SpanKind, client0.SpanKind)
}
if server.Name != "grpc.health.v1.Health/Check" {
t.Errorf("span name = %q", server.Name)
}
if server.Parent.SpanID() != client0.SpanContext.SpanID() {
t.Error("server span is not a child of the client span: metadata propagation failed")
}
if !strings.Contains(logs.String(), `"msg":"grpc request"`) || !strings.Contains(logs.String(), `"code":"OK"`) {
t.Errorf("missing gRPC access log: %s", logs.String())
}
}
func TestGRPC_StreamInstrumentation(t *testing.T) {
m := NewMetrics(MetricsConfig{})
tp, exp := newTestProvider(t)
client := startGRPC(t, NewHealth(HealthConfig{}), NewGRPCInterceptors(GRPCConfig{
Metrics: m,
TracerProvider: tp,
Propagator: testPropagator,
}))
stream, err := client.Watch(context.Background(), &healthpb.HealthCheckRequest{})
if err != nil {
t.Fatal(err)
}
_, err = stream.Recv()
if status.Code(err) != grpccodes.Unimplemented {
t.Fatalf("Recv error = %v, want Unimplemented", err)
}
if _, err := stream.Recv(); err == nil || err == io.EOF {
t.Fatalf("second Recv error = %v", err)
}
body := scrape(t, m)
for _, want := range []string{
`grpc_server_requests_total{code="Unimplemented",method="Watch",service="grpc.health.v1.Health"} 1`,
`grpc_client_requests_total{code="Unimplemented",method="Watch",service="grpc.health.v1.Health"} 1`,
} {
if !strings.Contains(body, want) {
t.Errorf("metrics missing %q\n%s", want, body)
}
}
spans := exp.GetSpans()
if len(spans) != 2 {
t.Fatalf("got %d spans, want 2", len(spans))
}
for _, s := range spans {
if s.Status.Code != codes.Error {
t.Errorf("span %q (%v) status = %v, want Error", s.Name, s.SpanKind, s.Status.Code)
}
}
}
func TestGRPC_Skip(t *testing.T) {
m := NewMetrics(MetricsConfig{})
client := startGRPC(t, NewHealth(HealthConfig{}), NewGRPCInterceptors(GRPCConfig{
Metrics: m,
Skip: func(string) bool { return true },
}))
if _, err := client.Check(context.Background(), &healthpb.HealthCheckRequest{}); err != nil {
t.Fatal(err)
}
if strings.Contains(scrape(t, m), "grpc_server_requests_total{") {
t.Error("skipped method was instrumented")
}
}
func TestSplitFullMethod(t *testing.T) {
tests := []struct{ in, service, method string }{
{"/pkg.Service/Method", "pkg.Service", "Method"},
{"/a.b.c.Svc/Do", "a.b.c.Svc", "Do"},
{"bad", "unknown", "bad"},
}
for _, tt := range tests {
s, m := splitFullMethod(tt.in)
if s != tt.service || m != tt.method {
t.Errorf("splitFullMethod(%q) = %q, %q", tt.in, s, m)
}
}
}
+230
View File
@@ -0,0 +1,230 @@
package obsx
import (
"bufio"
"bytes"
"context"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"google.golang.org/grpc"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)
func TestHTTPMiddleware_PanicAfterWriteIs500(t *testing.T) {
m := NewMetrics(MetricsConfig{})
h := NewHTTPMiddleware(HTTPServerConfig{Metrics: m})(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("partial"))
panic("boom")
}))
func() {
defer func() { _ = recover() }()
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
}()
if !strings.Contains(scrape(t, m), `http_server_requests_total{code="500",method="GET",route="unmatched"} 1`) {
t.Error("panic after a partial response not counted as 500")
}
}
func TestHTTPMiddleware_HijackAndReadFrom(t *testing.T) {
m := NewMetrics(MetricsConfig{})
var logs bytes.Buffer
logger, _ := NewLogger(LogConfig{Output: &logs})
mux := http.NewServeMux()
mux.HandleFunc("GET /ws", func(w http.ResponseWriter, r *http.Request) {
conn, _, err := http.NewResponseController(w).Hijack()
if err != nil {
t.Errorf("hijack: %v", err)
return
}
defer conn.Close()
_, _ = conn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n\r\n"))
})
mux.HandleFunc("GET /file", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(w, strings.NewReader("hello")) // goes through ReadFrom
})
srv := httptest.NewServer(NewHTTPMiddleware(HTTPServerConfig{Metrics: m, Logger: logger})(mux))
defer srv.Close()
conn, err := net.Dial("tcp", srv.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
_, _ = conn.Write([]byte("GET /ws HTTP/1.1\r\nHost: x\r\n\r\n"))
if line, _ := bufio.NewReader(conn).ReadString('\n'); !strings.Contains(line, "101") {
t.Fatalf("hijacked response = %q", line)
}
resp, err := http.Get(srv.URL + "/file")
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if string(body) != "hello" {
t.Errorf("body = %q", body)
}
if !strings.Contains(scrape(t, m), `http_server_requests_total{code="101",method="GET",route="/ws"} 1`) {
t.Errorf("hijacked request not counted as 101:\n%s", scrape(t, m))
}
if !strings.Contains(logs.String(), `"route":"/file","status":200`) || !strings.Contains(logs.String(), `"size":5`) {
t.Errorf("ReadFrom size not logged: %s", logs.String())
}
}
func TestHTTPTransport_HostFuncAndQueryRedaction(t *testing.T) {
m := NewMetrics(MetricsConfig{})
tp, exp := newTestProvider(t)
srv := httptest.NewServer(http.NotFoundHandler())
defer srv.Close()
client := &http.Client{Transport: NewHTTPTransport(nil, HTTPClientConfig{
Metrics: m,
TracerProvider: tp,
HostFunc: func(*http.Request) string { return "external" },
})}
resp, err := client.Get(srv.URL + "/hook?token=s3cret")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if !strings.Contains(scrape(t, m), `http_client_requests_total{code="404",host="external",method="GET"} 1`) {
t.Errorf("HostFunc not applied:\n%s", scrape(t, m))
}
for _, a := range exp.GetSpans()[0].Attributes {
if strings.Contains(a.Value.Emit(), "s3cret") {
t.Errorf("query string leaked into span attribute %s=%s", a.Key, a.Value.Emit())
}
}
}
func TestMetrics_FuncCollectorsPanicOnDuplicate(t *testing.T) {
m := NewMetrics(MetricsConfig{})
m.GaugeFunc("depth", "Queue depth", func() float64 { return 1 })
defer func() {
if recover() == nil {
t.Error("second GaugeFunc with the same name must panic, not be ignored")
}
}()
m.GaugeFunc("depth", "Queue depth", func() float64 { return 2 })
}
type blockingHealth struct {
healthpb.UnimplementedHealthServer
}
func (blockingHealth) Watch(_ *healthpb.HealthCheckRequest, s healthpb.Health_WatchServer) error {
<-s.Context().Done()
return s.Context().Err()
}
func TestGRPC_AbandonedClientStreamIsRecorded(t *testing.T) {
m := NewMetrics(MetricsConfig{})
client := startGRPCServer(t, blockingHealth{}, NewGRPCInterceptors(GRPCConfig{Metrics: m}))
ctx, cancel := context.WithCancel(context.Background())
if _, err := client.Watch(ctx, &healthpb.HealthCheckRequest{}); err != nil {
t.Fatal(err)
}
cancel() // walk away without reading the stream
want := `grpc_client_requests_total{code="Canceled",method="Watch",service="grpc.health.v1.Health"} 1`
for deadline := time.Now().Add(2 * time.Second); !strings.Contains(scrape(t, m), want); time.Sleep(5 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatalf("abandoned stream not recorded:\n%s", scrape(t, m))
}
}
}
func TestGRPC_ServerPanicIsRecorded(t *testing.T) {
m := NewMetrics(MetricsConfig{})
ic := NewGRPCInterceptors(GRPCConfig{Metrics: m})
func() {
defer func() {
if recover() != "boom" {
t.Error("panic not re-raised")
}
}()
_, _ = ic.UnaryServer(context.Background(), nil, &grpc.UnaryServerInfo{FullMethod: "/svc.S/M"},
func(context.Context, any) (any, error) { panic("boom") })
}()
body := scrape(t, m)
if !strings.Contains(body, `grpc_server_requests_total{code="Internal",method="M",service="svc.S"} 1`) ||
!strings.Contains(body, "grpc_server_requests_in_flight 0") {
t.Errorf("panic not recorded as Internal:\n%s", body)
}
}
func TestTracerConfig_ProtocolFromEnv(t *testing.T) {
t.Setenv("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf")
cfg := TracerConfig{Endpoint: "http://localhost:4318"}
cfg.defaults()
if cfg.Protocol != "http/protobuf" {
t.Fatalf("Protocol = %q", cfg.Protocol)
}
exp, err := newExporter(context.Background(), cfg)
if err != nil || exp == nil {
t.Fatalf("exporter = %v, err = %v", exp, err)
}
_ = exp.Shutdown(context.Background())
explicit := TracerConfig{Protocol: ProtocolGRPC}
explicit.defaults()
if explicit.Protocol != ProtocolGRPC {
t.Errorf("explicit Protocol overridden by env: %q", explicit.Protocol)
}
}
func TestHealth_CachesAndDoesNotStackHungChecks(t *testing.T) {
var calls atomic.Int32
h := NewHealth(HealthConfig{})
h.AddReadinessCheck("db", func(context.Context) error { calls.Add(1); return nil })
for range 5 {
if !h.CheckReadiness(context.Background()).Healthy() {
t.Fatal("unhealthy")
}
}
if n := calls.Load(); n != 1 {
t.Errorf("check ran %d times within the cache window, want 1", n)
}
calls.Store(0)
release := make(chan struct{})
defer close(release)
hung := NewHealth(HealthConfig{Timeout: 10 * time.Millisecond})
hung.AddReadinessCheck("stuck", func(context.Context) error { calls.Add(1); <-release; return nil }) // ignores ctx
hung.CheckReadiness(context.Background())
hung.readyCache.reset()
r := hung.CheckReadiness(context.Background())
if r.Healthy() || !strings.Contains(r.Checks["stuck"].Error, "still in progress") {
t.Errorf("report = %+v", r)
}
if n := calls.Load(); n != 1 {
t.Errorf("hung check started %d times, want 1", n)
}
}
func TestObserver_HTTPConfigIsApplied(t *testing.T) {
o, _, _ := newTestObserver(t, Config{HTTP: HTTPServerConfig{
RouteFunc: func(*http.Request) string { return "/users/{id}" },
Skip: func(r *http.Request) bool { return r.URL.Path == "/ws" },
}})
h := o.HTTPMiddleware(http.NotFoundHandler())
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/users/42", nil))
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/ws", nil))
body := scrape(t, o.Metrics())
if !strings.Contains(body, `http_server_requests_total{code="404",method="GET",route="/users/{id}"} 1`) {
t.Errorf("RouteFunc/Skip from Config.HTTP not applied:\n%s", body)
}
}
+289
View File
@@ -0,0 +1,289 @@
package obsx
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc/codes"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/status"
)
// Health check statuses reported in JSON responses.
const (
StatusOK = "ok"
StatusFail = "fail"
)
// CheckFunc checks a dependency and returns a non-nil error when it is unhealthy.
// It must respect ctx cancellation.
type CheckFunc func(ctx context.Context) error
// HealthConfig configures health checks.
type HealthConfig struct {
Timeout time.Duration // per-check timeout, default: 5s
Metrics *Metrics // optional: exports health_check_status{check,kind}
}
func (c *HealthConfig) defaults() {
if c.Timeout <= 0 {
c.Timeout = 5 * time.Second
}
}
type namedCheck struct {
name string
fn CheckFunc
busy *atomic.Bool // a run that outlived its timeout is still in progress
}
// healthCacheTTL bounds how often checks hit their dependencies, however
// often the probes (which may be reachable by clients) are called.
const healthCacheTTL = time.Second
type reportCache struct {
mu sync.Mutex // also serializes runs
at time.Time
report Report
}
func (c *reportCache) reset() {
c.mu.Lock()
c.at = time.Time{}
c.mu.Unlock()
}
// Health runs liveness and readiness checks and serves them over HTTP
// (Kubernetes probes) and gRPC (grpc.health.v1).
//
// Liveness answers "should the process be restarted?" and should only include
// checks of the process itself. Readiness answers "can it serve traffic?" and
// typically includes dependencies (database, cache, downstream services).
type Health struct {
timeout time.Duration
status *prometheus.GaugeVec
mu sync.RWMutex
liveness []namedCheck
ready []namedCheck
livenessCache, readyCache reportCache
notReady atomic.Bool
}
// NewHealth creates a Health with no checks; it reports healthy and ready.
func NewHealth(cfg HealthConfig) *Health {
cfg.defaults()
h := &Health{timeout: cfg.Timeout}
if cfg.Metrics != nil {
h.status = cfg.Metrics.base().Gauge("health_check_status",
"Result of the last health check run: 1 healthy, 0 failing.", "check", "kind")
}
return h
}
// AddLivenessCheck registers a check that affects the liveness probe.
func (h *Health) AddLivenessCheck(name string, fn CheckFunc) {
h.mu.Lock()
h.liveness = append(h.liveness, namedCheck{name: name, fn: fn, busy: new(atomic.Bool)})
h.mu.Unlock()
h.livenessCache.reset()
}
// AddReadinessCheck registers a check that affects the readiness probe.
func (h *Health) AddReadinessCheck(name string, fn CheckFunc) {
h.mu.Lock()
h.ready = append(h.ready, namedCheck{name: name, fn: fn, busy: new(atomic.Bool)})
h.mu.Unlock()
h.readyCache.reset()
}
// SetReady overrides readiness. Call SetReady(false) during startup warm-up or
// at the beginning of graceful shutdown so that load balancers stop sending
// traffic; readiness checks are not run while the service is marked not ready.
func (h *Health) SetReady(ready bool) {
h.notReady.Store(!ready)
}
// Report is the result of running a set of checks.
type Report struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Checks map[string]CheckResult `json:"checks,omitempty"`
}
// CheckResult is the outcome of a single check.
type CheckResult struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Duration string `json:"duration"`
}
// Healthy reports whether all checks passed.
func (r Report) Healthy() bool { return r.Status == StatusOK }
// CheckLiveness runs all liveness checks concurrently. Results are reused for
// up to a second, so frequent probes do not hammer the checked dependencies.
func (h *Health) CheckLiveness(ctx context.Context) Report {
h.mu.RLock()
checks := h.liveness
h.mu.RUnlock()
return h.run(ctx, "liveness", checks, &h.livenessCache)
}
// CheckReadiness runs all readiness checks concurrently. It fails immediately
// when the service was marked not ready with SetReady(false).
func (h *Health) CheckReadiness(ctx context.Context) Report {
if h.notReady.Load() {
return Report{Status: StatusFail, Error: "service is not ready"}
}
h.mu.RLock()
checks := h.ready
h.mu.RUnlock()
return h.run(ctx, "readiness", checks, &h.readyCache)
}
func (h *Health) run(ctx context.Context, kind string, checks []namedCheck, cache *reportCache) Report {
report := Report{Status: StatusOK}
if len(checks) == 0 {
return report
}
cache.mu.Lock()
defer cache.mu.Unlock()
if !cache.at.IsZero() && time.Since(cache.at) < healthCacheTTL {
return cache.report
}
results := make([]CheckResult, len(checks))
var wg sync.WaitGroup
for i, c := range checks {
wg.Add(1)
go func() {
defer wg.Done()
results[i] = h.runOne(ctx, c)
}()
}
wg.Wait()
report.Checks = make(map[string]CheckResult, len(checks))
for i, c := range checks {
res := results[i]
report.Checks[c.name] = res
healthy := 1.0
if res.Status != StatusOK {
report.Status = StatusFail
healthy = 0
}
if h.status != nil {
h.status.WithLabelValues(c.name, kind).Set(healthy)
}
}
if ctx.Err() == nil { // a cancelled caller must not fail the probe for everyone
cache.at, cache.report = time.Now(), report
}
return report
}
func (h *Health) runOne(ctx context.Context, c namedCheck) CheckResult {
// A check that ignores ctx must not pile up one goroutine per probe.
if !c.busy.CompareAndSwap(false, true) {
return CheckResult{Status: StatusFail, Error: "previous run is still in progress", Duration: "0s"}
}
ctx, cancel := context.WithTimeout(ctx, h.timeout)
defer cancel()
start := time.Now()
done := make(chan error, 1)
go func() {
defer c.busy.Store(false)
defer func() {
if rec := recover(); rec != nil {
done <- fmt.Errorf("panic: %v", rec)
}
}()
done <- c.fn(ctx)
}()
var err error
select {
case err = <-done:
case <-ctx.Done():
err = ctx.Err()
if errors.Is(err, context.DeadlineExceeded) {
err = fmt.Errorf("timed out after %s", h.timeout)
}
}
res := CheckResult{Status: StatusOK, Duration: time.Since(start).String()}
if err != nil {
res.Status = StatusFail
res.Error = err.Error()
}
return res
}
// LivenessHandler serves liveness checks: 200 when healthy, 503 otherwise.
func (h *Health) LivenessHandler() http.Handler {
return reportHandler(h.CheckLiveness)
}
// ReadinessHandler serves readiness checks: 200 when ready, 503 otherwise.
func (h *Health) ReadinessHandler() http.Handler {
return reportHandler(h.CheckReadiness)
}
func reportHandler(check func(context.Context) Report) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
report := check(r.Context())
code := http.StatusOK
if !report.Healthy() {
code = http.StatusServiceUnavailable
}
writeJSON(w, code, report)
})
}
// GRPCServer returns a grpc.health.v1 implementation backed by readiness
// checks. Register it with healthpb.RegisterHealthServer(srv, h.GRPCServer()).
// Watch is not supported.
func (h *Health) GRPCServer() healthpb.HealthServer {
return &grpcHealthServer{h: h}
}
type grpcHealthServer struct {
healthpb.UnimplementedHealthServer
h *Health
}
func (s *grpcHealthServer) Check(ctx context.Context, _ *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
if err := ctx.Err(); err != nil {
return nil, status.FromContextError(err).Err()
}
st := healthpb.HealthCheckResponse_SERVING
if !s.h.CheckReadiness(ctx).Healthy() {
st = healthpb.HealthCheckResponse_NOT_SERVING
}
return &healthpb.HealthCheckResponse{Status: st}, nil
}
func (s *grpcHealthServer) Watch(*healthpb.HealthCheckRequest, healthpb.Health_WatchServer) error {
return status.Error(codes.Unimplemented, "watch is not supported")
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(code)
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
_ = enc.Encode(v)
}
+119
View File
@@ -0,0 +1,119 @@
package obsx
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestHealth_NoChecks(t *testing.T) {
h := NewHealth(HealthConfig{})
if r := h.CheckLiveness(context.Background()); !r.Healthy() {
t.Errorf("liveness = %+v, want ok", r)
}
if r := h.CheckReadiness(context.Background()); !r.Healthy() {
t.Errorf("readiness = %+v, want ok", r)
}
}
func TestHealth_ReadinessChecks(t *testing.T) {
m := NewMetrics(MetricsConfig{})
h := NewHealth(HealthConfig{Timeout: 50 * time.Millisecond, Metrics: m})
h.AddReadinessCheck("db", func(ctx context.Context) error { return nil })
h.AddReadinessCheck("cache", func(ctx context.Context) error { return errors.New("connection refused") })
h.AddReadinessCheck("slow", func(ctx context.Context) error {
<-ctx.Done()
return ctx.Err()
})
h.AddReadinessCheck("stuck", func(ctx context.Context) error {
time.Sleep(time.Second) // ignores ctx; must not block the probe
return nil
})
h.AddReadinessCheck("panics", func(ctx context.Context) error { panic("oops") })
start := time.Now()
r := h.CheckReadiness(context.Background())
if elapsed := time.Since(start); elapsed > 500*time.Millisecond {
t.Errorf("readiness took %s, checks must time out", elapsed)
}
if r.Healthy() {
t.Fatal("readiness must fail")
}
if r.Checks["db"].Status != StatusOK {
t.Errorf("db = %+v", r.Checks["db"])
}
if c := r.Checks["cache"]; c.Status != StatusFail || c.Error != "connection refused" {
t.Errorf("cache = %+v", c)
}
if c := r.Checks["stuck"]; c.Status != StatusFail || !strings.Contains(c.Error, "timed out") {
t.Errorf("stuck = %+v", c)
}
if c := r.Checks["panics"]; c.Status != StatusFail || !strings.Contains(c.Error, "panic: oops") {
t.Errorf("panics = %+v", c)
}
// Liveness is independent of readiness checks.
if !h.CheckLiveness(context.Background()).Healthy() {
t.Error("liveness must not include readiness checks")
}
body := scrape(t, m)
for _, want := range []string{
`health_check_status{check="db",kind="readiness"} 1`,
`health_check_status{check="cache",kind="readiness"} 0`,
} {
if !strings.Contains(body, want) {
t.Errorf("metrics missing %q", want)
}
}
}
func TestHealth_SetReady(t *testing.T) {
h := NewHealth(HealthConfig{})
called := false
h.AddReadinessCheck("db", func(ctx context.Context) error { called = true; return nil })
h.SetReady(false)
r := h.CheckReadiness(context.Background())
if r.Healthy() || called {
t.Errorf("not-ready service must fail without running checks: %+v called=%v", r, called)
}
h.SetReady(true)
if !h.CheckReadiness(context.Background()).Healthy() || !called {
t.Error("ready service must run checks and pass")
}
}
func TestHealth_Handlers(t *testing.T) {
h := NewHealth(HealthConfig{})
h.AddLivenessCheck("deadlock", func(ctx context.Context) error { return errors.New("stuck") })
w := httptest.NewRecorder()
h.LivenessHandler().ServeHTTP(w, httptest.NewRequest("GET", "/healthz", nil))
if w.Code != http.StatusServiceUnavailable {
t.Errorf("liveness code = %d, want 503", w.Code)
}
var r Report
if err := json.Unmarshal(w.Body.Bytes(), &r); err != nil {
t.Fatal(err)
}
if r.Status != StatusFail || r.Checks["deadlock"].Error != "stuck" {
t.Errorf("unexpected report: %+v", r)
}
if ct := w.Header().Get("Content-Type"); ct != "application/json" {
t.Errorf("Content-Type = %q", ct)
}
w = httptest.NewRecorder()
h.ReadinessHandler().ServeHTTP(w, httptest.NewRequest("GET", "/readyz", nil))
if w.Code != http.StatusOK {
t.Errorf("readiness code = %d, want 200", w.Code)
}
}
+87
View File
@@ -0,0 +1,87 @@
package obsx
import (
"net/http"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
"go.opentelemetry.io/otel/trace"
)
// HTTPMiddleware returns server middleware that traces every request
// (continuing the trace from incoming headers) and, when m is not nil, records
// the http_requests_total{method,route,status} counter and the
// http_request_duration_seconds{method,route} histogram.
//
// The route is the matched http.ServeMux pattern (Request.Pattern), so wrap
// the mux itself; unmatched requests are reported as route "unmatched".
//
// Deprecated: use NewHTTPMiddleware (or Observer.HTTPMiddleware), which adds
// access logs, in-flight and exemplar support and uses the fleet-wide
// http_server_* metric names. HTTPMiddleware keeps its v1.0.0 metric names.
func HTTPMiddleware(m *Metrics) func(http.Handler) http.Handler {
var requests *prometheus.CounterVec
var duration *prometheus.HistogramVec
if m != nil {
requests = m.Counter("http_requests_total", "Total HTTP requests served.", "method", "route", "status")
duration = m.Histogram("http_request_duration_seconds", "HTTP request duration in seconds.", nil, "method", "route")
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
method := normalizeMethod(r.Method)
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
ctx, span := otel.Tracer(tracerName).Start(ctx, method,
trace.WithSpanKind(trace.SpanKindServer),
trace.WithAttributes(semconv.HTTPRequestMethodKey.String(method), semconv.URLPath(r.URL.Path)),
)
defer span.End()
rw := &responseWriter{ResponseWriter: w}
r = r.WithContext(ctx)
defer func() {
// A panic propagates to net/http, which answers 500 or drops the connection.
p := recover()
status := rw.status
switch {
case p != nil:
status = http.StatusInternalServerError
case status == 0:
status = http.StatusOK
}
route := r.Pattern // set by ServeMux on this request during ServeHTTP
if route == "" {
route = routeUnmatched
} else {
span.SetName(route)
span.SetAttributes(semconv.HTTPRoute(route))
}
span.SetAttributes(semconv.HTTPResponseStatusCode(status))
if status >= 500 {
span.SetStatus(codes.Error, http.StatusText(status))
}
if m != nil {
requests.WithLabelValues(method, route, strconv.Itoa(status)).Inc()
duration.WithLabelValues(method, route).Observe(time.Since(start).Seconds())
}
if p != nil {
panic(p)
}
}()
next.ServeHTTP(rw, r)
})
}
}
// HTTPTransport wraps base (nil means http.DefaultTransport) so that every
// outgoing request gets a client span and carries the trace context headers.
//
// Deprecated: use NewHTTPTransport, which HTTPTransport now calls without metrics.
func HTTPTransport(base http.RoundTripper) http.RoundTripper {
return NewHTTPTransport(base, HTTPClientConfig{})
}
+136
View File
@@ -0,0 +1,136 @@
package obsx
import (
"bytes"
"context"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
)
const parentTrace = "4bf92f3577b34da6a3ce929d0e0e4736"
func setupPropagation(t *testing.T) *tracetest.InMemoryExporter {
t.Helper()
prevTP, prevProp := otel.GetTracerProvider(), otel.GetTextMapPropagator()
t.Cleanup(func() {
otel.SetTracerProvider(prevTP)
otel.SetTextMapPropagator(prevProp)
})
otel.SetTextMapPropagator(propagation.TraceContext{})
return setupTestTracer(t)
}
func TestHTTPMiddleware(t *testing.T) {
exp := setupPropagation(t)
m := NewMetrics(MetricsConfig{Namespace: "test"})
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {})
mux.HandleFunc("GET /fail", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
})
mux.HandleFunc("GET /panic", func(w http.ResponseWriter, r *http.Request) { panic("boom") })
h := HTTPMiddleware(m)(mux)
req := httptest.NewRequest("GET", "/users/42", nil)
req.Header.Set("traceparent", "00-"+parentTrace+"-00f067aa0ba902b7-01")
h.ServeHTTP(httptest.NewRecorder(), req)
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/fail", nil))
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("WEIRD", "/nope", nil))
func() {
defer func() {
if recover() == nil {
t.Error("expected the handler panic to propagate")
}
}()
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/panic", nil))
}()
spans := exp.GetSpans()
if len(spans) != 4 {
t.Fatalf("expected 4 spans, got %d", len(spans))
}
if spans[0].Name != "GET /users/{id}" {
t.Errorf("span name = %q", spans[0].Name)
}
if got := spans[0].SpanContext.TraceID().String(); got != parentTrace {
t.Errorf("trace not continued from header: trace id %s", got)
}
body := scrape(t, m)
for _, want := range []string{
`test_http_requests_total{method="GET",route="GET /users/{id}",status="200"} 1`,
`test_http_requests_total{method="GET",route="GET /fail",status="500"} 1`,
`test_http_requests_total{method="GET",route="GET /panic",status="500"} 1`,
`test_http_requests_total{method="OTHER",route="unmatched",status="404"} 1`,
`test_http_request_duration_seconds_count{method="GET",route="GET /users/{id}"} 1`,
} {
if !strings.Contains(body, want) {
t.Errorf("missing %q in:\n%s", want, body)
}
}
}
func TestHTTPMiddleware_NilMetrics(t *testing.T) {
w := httptest.NewRecorder()
HTTPMiddleware(nil)(http.NotFoundHandler()).ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
if w.Code != http.StatusNotFound {
t.Errorf("status = %d", w.Code)
}
}
func TestHTTPTransport_PropagatesTrace(t *testing.T) {
exp := setupPropagation(t)
var got string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.Header.Get("traceparent")
}))
defer srv.Close()
ctx, parent := StartSpan(context.Background(), "parent")
req, _ := http.NewRequestWithContext(ctx, "GET", srv.URL, nil)
resp, err := (&http.Client{Transport: HTTPTransport(nil)}).Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
parent.End()
if !strings.Contains(got, parent.SpanContext().TraceID().String()) {
t.Errorf("traceparent %q does not carry trace %s", got, parent.SpanContext().TraceID())
}
if req.Header.Get("traceparent") != "" {
t.Error("caller's request was modified")
}
if n := len(exp.GetSpans()); n != 2 {
t.Errorf("expected parent + client span, got %d", n)
}
}
func TestLogHandler(t *testing.T) {
setupPropagation(t)
var buf bytes.Buffer
log := slog.New(LogHandler(slog.NewJSONHandler(&buf, nil))).With("k", "v")
ctx, span := StartSpan(context.Background(), "op")
defer span.End()
log.InfoContext(ctx, "hello")
log.Info("no span")
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
if !strings.Contains(lines[0], `"trace_id":"`+span.SpanContext().TraceID().String()+`"`) ||
!strings.Contains(lines[0], `"span_id":"`+span.SpanContext().SpanID().String()+`"`) {
t.Errorf("trace ids missing: %s", lines[0])
}
if strings.Contains(lines[1], "trace_id") {
t.Errorf("unexpected trace id: %s", lines[1])
}
}
+132
View File
@@ -0,0 +1,132 @@
package obsx
import (
"net/http"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
// HTTPClientConfig configures the instrumented HTTP client transport.
type HTTPClientConfig struct {
Metrics *Metrics // nil disables metrics
TracerProvider trace.TracerProvider // nil: global provider
Propagator propagation.TextMapPropagator // nil: global propagator
Buckets []float64 // latency buckets in seconds, default: prometheus.DefBuckets
// HostFunc returns the host metric label, default: the request URL host.
// When hosts come from users (webhooks, fetch-by-URL) return a fixed
// value such as "external" to keep metric cardinality bounded.
HostFunc func(*http.Request) string
}
func (c *HTTPClientConfig) defaults() {
if c.TracerProvider == nil {
c.TracerProvider = otel.GetTracerProvider()
}
if c.Propagator == nil {
c.Propagator = otel.GetTextMapPropagator()
}
if c.HostFunc == nil {
c.HostFunc = func(r *http.Request) string { return r.URL.Host }
}
}
type httpClientMetrics struct {
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
}
func newHTTPClientMetrics(m *Metrics, buckets []float64) *httpClientMetrics {
m = m.base()
return &httpClientMetrics{
requests: m.Counter("http_client_requests_total",
"Total number of outgoing HTTP requests.", "method", "host", "code"),
duration: m.Histogram("http_client_request_duration_seconds",
"Duration of outgoing HTTP requests until response headers are received.", buckets, "method", "host", "code"),
}
}
type clientTransport struct {
base http.RoundTripper
tracer trace.Tracer
propagator propagation.TextMapPropagator
metrics *httpClientMetrics
hostFunc func(*http.Request) string
}
// NewHTTPTransport wraps base (http.DefaultTransport when nil) with client
// spans, trace context propagation and metrics:
// http_client_requests_total and http_client_request_duration_seconds
// (labels method, host, code; code is "error" for transport failures).
func NewHTTPTransport(base http.RoundTripper, cfg HTTPClientConfig) http.RoundTripper {
cfg.defaults()
if base == nil {
base = http.DefaultTransport
}
t := &clientTransport{
base: base,
tracer: cfg.TracerProvider.Tracer(tracerName),
propagator: cfg.Propagator,
hostFunc: cfg.HostFunc,
}
if cfg.Metrics != nil {
t.metrics = newHTTPClientMetrics(cfg.Metrics, cfg.Buckets)
}
return t
}
// RoundTrip implements http.RoundTripper.
func (t *clientTransport) RoundTrip(req *http.Request) (*http.Response, error) {
start := time.Now()
method := normalizeMethod(req.Method)
ctx, span := t.tracer.Start(req.Context(), method,
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.String("http.request.method", method),
attribute.String("server.address", req.URL.Hostname()),
attribute.String("url.full", redactURL(req)),
),
)
defer span.End()
// RoundTrippers must not modify the caller's request.
req = req.Clone(ctx)
t.propagator.Inject(ctx, propagation.HeaderCarrier(req.Header))
resp, err := t.base.RoundTrip(req)
code := "error"
if err != nil {
failSpan(span, err)
} else {
code = strconv.Itoa(resp.StatusCode)
span.SetAttributes(attribute.Int("http.response.status_code", resp.StatusCode))
if resp.StatusCode >= 400 {
span.SetStatus(codes.Error, http.StatusText(resp.StatusCode))
}
}
if t.metrics != nil {
host := t.hostFunc(req)
t.metrics.requests.WithLabelValues(method, host, code).Inc()
observe(ctx, t.metrics.duration.WithLabelValues(method, host, code), time.Since(start).Seconds())
}
return resp, err
}
// redactURL returns the request URL without user credentials and without the
// query string, which often carries tokens and signatures.
func redactURL(req *http.Request) string {
u := *req.URL
u.User = nil
u.RawQuery = ""
return u.String()
}
+103
View File
@@ -0,0 +1,103 @@
package obsx
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
func TestHTTPTransport_PropagationAndMetrics(t *testing.T) {
m := NewMetrics(MetricsConfig{})
tp, exp := newTestProvider(t)
var gotTraceparent string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotTraceparent = r.Header.Get("traceparent")
if r.URL.Path == "/missing" {
w.WriteHeader(http.StatusNotFound)
}
}))
defer srv.Close()
client := &http.Client{Transport: NewHTTPTransport(nil, HTTPClientConfig{
Metrics: m,
TracerProvider: tp,
Propagator: testPropagator,
})}
req, _ := http.NewRequest("GET", srv.URL+"/ok", nil)
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if req.Header.Get("traceparent") != "" {
t.Error("transport modified the caller's request headers")
}
resp, err = client.Get(srv.URL + "/missing")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
spans := exp.GetSpans()
if len(spans) != 2 {
t.Fatalf("got %d spans, want 2", len(spans))
}
if spans[0].SpanKind != trace.SpanKindClient {
t.Errorf("span kind = %v, want client", spans[0].SpanKind)
}
sc := spans[1].SpanContext
if !strings.Contains(gotTraceparent, sc.TraceID().String()) || !strings.Contains(gotTraceparent, sc.SpanID().String()) {
t.Errorf("traceparent %q does not reference client span %s/%s", gotTraceparent, sc.TraceID(), sc.SpanID())
}
host := strings.TrimPrefix(srv.URL, "http://")
body := scrape(t, m)
for _, want := range []string{
`http_client_requests_total{code="200",host="` + host + `",method="GET"} 1`,
`http_client_requests_total{code="404",host="` + host + `",method="GET"} 1`,
`http_client_request_duration_seconds_count{code="200",host="` + host + `",method="GET"} 1`,
} {
if !strings.Contains(body, want) {
t.Errorf("metrics missing %q", want)
}
}
}
func TestHTTPTransport_Error(t *testing.T) {
m := NewMetrics(MetricsConfig{})
tp, exp := newTestProvider(t)
client := &http.Client{Transport: NewHTTPTransport(nil, HTTPClientConfig{Metrics: m, TracerProvider: tp, Propagator: propagation.TraceContext{}})}
srv := httptest.NewServer(http.NotFoundHandler())
addr := srv.URL
srv.Close() // connection refused
if _, err := client.Get(addr); err == nil {
t.Fatal("expected error")
}
if !strings.Contains(scrape(t, m), `code="error"`) {
t.Error("transport error not counted with code=error")
}
if spans := exp.GetSpans(); len(spans) != 1 || len(spans[0].Events) == 0 {
t.Error("transport error not recorded on span")
}
}
func TestRedactURL(t *testing.T) {
u, _ := url.Parse("https://user:secret@example.com/path?q=1")
got := redactURL(&http.Request{URL: u})
if strings.Contains(got, "secret") || strings.Contains(got, "user") {
t.Errorf("credentials not redacted: %s", got)
}
if got != "https://example.com/path" {
t.Errorf("redactURL = %q", got)
}
}
+303
View File
@@ -0,0 +1,303 @@
package obsx
import (
"bufio"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
// routeUnmatched is the route label for requests whose route is unknown.
// Raw paths are never used as labels to keep metric cardinality bounded.
const routeUnmatched = "unmatched"
// HTTPServerConfig configures the HTTP server middleware.
type HTTPServerConfig struct {
Metrics *Metrics // nil disables metrics
Logger *slog.Logger // nil disables access logs
TracerProvider trace.TracerProvider // nil: global provider
// Propagator extracts the incoming trace context; nil: global propagator.
// Sampling follows the caller's decision, so on endpoints reachable by
// untrusted clients set propagation.NewCompositeTextMapPropagator() to
// ignore incoming trace headers.
Propagator propagation.TextMapPropagator
// RouteFunc returns the low-cardinality route template of a request
// (e.g. "/users/{id}"). It is called after the handler has run. The
// default uses http.Request.Pattern set by http.ServeMux; when the
// middleware wraps an *http.ServeMux directly the pattern is resolved even
// if inner middleware replaced the request. Unknown routes are reported
// as "unmatched".
//
// For chi: func(r *http.Request) string { return chi.RouteContext(r.Context()).RoutePattern() }
RouteFunc func(r *http.Request) string
Skip func(r *http.Request) bool // requests for which Skip returns true are not instrumented
Buckets []float64 // latency buckets in seconds, default: prometheus.DefBuckets
TraceIDHeader string // if set, the trace ID is returned in this response header, e.g. "X-Trace-Id"
}
func (c *HTTPServerConfig) defaults() {
if c.TracerProvider == nil {
c.TracerProvider = otel.GetTracerProvider()
}
if c.Propagator == nil {
c.Propagator = otel.GetTextMapPropagator()
}
}
type httpServerMetrics struct {
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
inflight prometheus.Gauge
}
func newHTTPServerMetrics(m *Metrics, buckets []float64) *httpServerMetrics {
m = m.base()
return &httpServerMetrics{
requests: m.Counter("http_server_requests_total",
"Total number of HTTP requests handled by the server.", "method", "route", "code"),
duration: m.Histogram("http_server_request_duration_seconds",
"Duration of HTTP requests handled by the server.", buckets, "method", "route", "code"),
inflight: m.Gauge("http_server_requests_in_flight",
"Number of HTTP requests currently being handled by the server.").WithLabelValues(),
}
}
// NewHTTPMiddleware returns middleware that instruments HTTP handlers with
// tracing (incoming context extraction, server spans), RED metrics and access
// logs. It is compatible with any router accepting func(http.Handler) http.Handler.
//
// Metrics: http_server_requests_total, http_server_request_duration_seconds
// (labels method, route, code) and http_server_requests_in_flight.
//
// Panics are recorded as 500 responses and re-raised.
func NewHTTPMiddleware(cfg HTTPServerConfig) func(http.Handler) http.Handler {
cfg.defaults()
var metrics *httpServerMetrics
if cfg.Metrics != nil {
metrics = newHTTPServerMetrics(cfg.Metrics, cfg.Buckets)
}
tracer := cfg.TracerProvider.Tracer(tracerName)
return func(next http.Handler) http.Handler {
routeFunc := cfg.RouteFunc
if routeFunc == nil {
mux, _ := next.(*http.ServeMux)
routeFunc = func(r *http.Request) string { return patternRoute(r, mux) }
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if cfg.Skip != nil && cfg.Skip(r) {
next.ServeHTTP(w, r)
return
}
start := time.Now()
method := normalizeMethod(r.Method)
ctx := cfg.Propagator.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
ctx, span := tracer.Start(ctx, method,
trace.WithSpanKind(trace.SpanKindServer),
trace.WithAttributes(
attribute.String("http.request.method", method),
attribute.String("url.path", r.URL.Path),
attribute.String("url.scheme", requestScheme(r)),
attribute.String("server.address", r.Host),
attribute.String("client.address", clientIP(r.RemoteAddr)),
attribute.String("user_agent.original", r.UserAgent()),
),
)
if cfg.TraceIDHeader != "" && span.SpanContext().HasTraceID() {
w.Header().Set(cfg.TraceIDHeader, span.SpanContext().TraceID().String())
}
if metrics != nil {
metrics.inflight.Inc()
}
rw := &responseWriter{ResponseWriter: w}
r = r.WithContext(ctx)
defer func() {
rec := recover()
status := rw.status
switch {
case rec != nil: // also after a partial response: the connection is aborted
status = http.StatusInternalServerError
case status == 0:
status = http.StatusOK
}
route := routeFunc(r)
if route == "" {
route = routeUnmatched
}
code := strconv.Itoa(status)
elapsed := time.Since(start)
if route != routeUnmatched {
span.SetName(method + " " + route)
span.SetAttributes(attribute.String("http.route", route))
}
span.SetAttributes(
attribute.Int("http.response.status_code", status),
attribute.Int64("http.response.body.size", rw.size),
)
if rec != nil {
span.RecordError(fmt.Errorf("panic: %v", rec), trace.WithStackTrace(true))
}
if status >= 500 {
span.SetStatus(codes.Error, http.StatusText(status))
}
if metrics != nil {
metrics.inflight.Dec()
metrics.requests.WithLabelValues(method, route, code).Inc()
observe(ctx, metrics.duration.WithLabelValues(method, route, code), elapsed.Seconds())
}
if cfg.Logger != nil {
level := slog.LevelInfo
if status >= 500 {
level = slog.LevelError
}
attrs := []slog.Attr{
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("route", route),
slog.Int("status", status),
durationAttr(elapsed),
slog.Int64("size", rw.size),
slog.String("remote", clientIP(r.RemoteAddr)),
}
if rec != nil {
attrs = append(attrs, slog.Any("panic", rec))
}
cfg.Logger.LogAttrs(ctx, level, "http request", attrs...)
}
span.End()
if rec != nil {
panic(rec)
}
}()
next.ServeHTTP(rw, r)
})
}
}
// patternRoute derives the route from the ServeMux pattern ("GET /users/{id}"
// becomes "/users/{id}"). If the request was copied by inner middleware the
// pattern is resolved through mux, when known.
func patternRoute(r *http.Request, mux *http.ServeMux) string {
pattern := r.Pattern
if pattern == "" && mux != nil {
_, pattern = mux.Handler(r)
}
if pattern == "" {
return routeUnmatched
}
if i := strings.IndexAny(pattern, " \t"); i >= 0 {
pattern = strings.TrimLeft(pattern[i:], " \t")
}
return pattern
}
// normalizeMethod maps non-standard methods to "OTHER" to bound cardinality.
func normalizeMethod(m string) string {
switch m {
case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch,
http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace:
return m
default:
return "OTHER"
}
}
func requestScheme(r *http.Request) string {
if r.TLS != nil {
return "https"
}
return "http"
}
func clientIP(remoteAddr string) string {
if host, _, err := net.SplitHostPort(remoteAddr); err == nil {
return host
}
return remoteAddr
}
// responseWriter captures the status code and body size. It supports
// http.Flusher, http.Hijacker, io.ReaderFrom and http.ResponseController
// (via Unwrap).
type responseWriter struct {
http.ResponseWriter
status int
size int64
wroteHeader bool
}
func (w *responseWriter) WriteHeader(code int) {
if !w.wroteHeader && code >= 200 {
w.status = code
w.wroteHeader = true
}
w.ResponseWriter.WriteHeader(code)
}
func (w *responseWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
n, err := w.ResponseWriter.Write(b)
w.size += int64(n)
return n, err
}
func (w *responseWriter) ReadFrom(src io.Reader) (int64, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
n, err := io.Copy(w.ResponseWriter, src)
w.size += n
return n, err
}
func (w *responseWriter) Flush() {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
_ = http.NewResponseController(w.ResponseWriter).Flush()
}
func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
conn, rw, err := http.NewResponseController(w.ResponseWriter).Hijack()
if err == nil && !w.wroteHeader {
w.status = http.StatusSwitchingProtocols
w.wroteHeader = true
}
return conn, rw, err
}
func (w *responseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
+226
View File
@@ -0,0 +1,226 @@
package obsx
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
"go.opentelemetry.io/otel/trace"
)
func newTestProvider(t *testing.T) (*sdktrace.TracerProvider, *tracetest.InMemoryExporter) {
t.Helper()
exp := tracetest.NewInMemoryExporter()
tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp))
t.Cleanup(func() { _ = tp.Shutdown(context.Background()) })
return tp, exp
}
var testPropagator = propagation.TraceContext{}
func TestHTTPMiddleware_MetricsAndSpans(t *testing.T) {
m := NewMetrics(MetricsConfig{Namespace: "ignored"})
tp, exp := newTestProvider(t)
var logs bytes.Buffer
logger, _ := NewLogger(LogConfig{Output: &logs})
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("user"))
})
mux.HandleFunc("POST /fail", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadGateway)
})
h := NewHTTPMiddleware(HTTPServerConfig{
Metrics: m,
Logger: logger,
TracerProvider: tp,
Propagator: testPropagator,
TraceIDHeader: "X-Trace-Id",
})(mux)
for _, id := range []string{"1", "2"} {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", "/users/"+id, nil))
if w.Header().Get("X-Trace-Id") == "" {
t.Error("missing X-Trace-Id response header")
}
}
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", "/fail", nil))
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/nope", nil))
body := scrape(t, m)
for _, want := range []string{
`http_server_requests_total{code="200",method="GET",route="/users/{id}"} 2`,
`http_server_requests_total{code="502",method="POST",route="/fail"} 1`,
`http_server_requests_total{code="404",method="GET",route="unmatched"} 1`,
`http_server_request_duration_seconds_count{code="200",method="GET",route="/users/{id}"} 2`,
`http_server_requests_in_flight 0`,
} {
if !strings.Contains(body, want) {
t.Errorf("metrics missing %q", want)
}
}
if strings.Contains(body, "ignored_http") {
t.Error("built-in metrics must not use the configured namespace")
}
spans := exp.GetSpans()
if len(spans) != 4 {
t.Fatalf("got %d spans, want 4", len(spans))
}
if spans[0].Name != "GET /users/{id}" || spans[0].SpanKind != trace.SpanKindServer {
t.Errorf("span = %q kind %v, want %q server", spans[0].Name, spans[0].SpanKind, "GET /users/{id}")
}
if spans[2].Status.Code != codes.Error {
t.Errorf("5xx span status = %v, want Error", spans[2].Status.Code)
}
lines := strings.Split(strings.TrimSpace(logs.String()), "\n")
if len(lines) != 4 {
t.Fatalf("got %d access log lines, want 4:\n%s", len(lines), logs.String())
}
var rec map[string]any
if err := json.Unmarshal([]byte(lines[2]), &rec); err != nil {
t.Fatal(err)
}
if rec["level"] != "ERROR" || rec["route"] != "/fail" || rec["status"] != float64(502) || rec["trace_id"] == nil {
t.Errorf("unexpected access log record: %v", rec)
}
}
func TestHTTPMiddleware_PropagatesParent(t *testing.T) {
tp, exp := newTestProvider(t)
h := NewHTTPMiddleware(HTTPServerConfig{TracerProvider: tp, Propagator: testPropagator})(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
parentCtx, parent := tp.Tracer("client").Start(context.Background(), "client")
req := httptest.NewRequest("GET", "/", nil)
testPropagator.Inject(parentCtx, propagation.HeaderCarrier(req.Header))
h.ServeHTTP(httptest.NewRecorder(), req)
parent.End()
server := exp.GetSpans()[0]
if server.Parent.SpanID() != parent.SpanContext().SpanID() {
t.Errorf("server span parent = %s, want %s", server.Parent.SpanID(), parent.SpanContext().SpanID())
}
if server.SpanContext.TraceID() != parent.SpanContext().TraceID() {
t.Error("server span not in the caller's trace")
}
}
func TestHTTPMiddleware_RouteWithInnerMiddleware(t *testing.T) {
m := NewMetrics(MetricsConfig{})
mux := http.NewServeMux()
mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) {})
// Inner middleware replaces the request, so r.Pattern is not visible to
// the outer middleware; route must still be resolved.
inner := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), struct{}{}, 1)))
})
}
mw := NewHTTPMiddleware(HTTPServerConfig{Metrics: m})
// Wrapping the mux directly resolves the route through r.Pattern.
mw(mux).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/items/1", nil))
// Through foreign middleware the route is unknown unless RouteFunc is set.
mw(inner(mux)).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/items/2", nil))
NewHTTPMiddleware(HTTPServerConfig{Metrics: m, RouteFunc: func(r *http.Request) string {
_, p := mux.Handler(r)
return strings.TrimPrefix(p, "GET ")
}})(inner(mux)).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/items/3", nil))
body := scrape(t, m)
if !strings.Contains(body, `http_server_requests_total{code="200",method="GET",route="/items/{id}"} 2`) {
t.Errorf("expected 2 requests on /items/{id}:\n%s", body)
}
if !strings.Contains(body, `http_server_requests_total{code="200",method="GET",route="unmatched"} 1`) {
t.Errorf("expected 1 unmatched request:\n%s", body)
}
}
func TestHTTPMiddleware_Panic(t *testing.T) {
m := NewMetrics(MetricsConfig{})
tp, exp := newTestProvider(t)
h := NewHTTPMiddleware(HTTPServerConfig{Metrics: m, TracerProvider: tp})(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { panic("boom") }))
func() {
defer func() {
if rec := recover(); rec != "boom" {
t.Errorf("panic not re-raised, got %v", rec)
}
}()
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
}()
if !strings.Contains(scrape(t, m), `http_server_requests_total{code="500",method="GET",route="unmatched"} 1`) {
t.Error("panic not counted as 500")
}
if spans := exp.GetSpans(); len(spans) != 1 || spans[0].Status.Code != codes.Error {
t.Errorf("expected one failed span, got %+v", spans)
}
}
func TestHTTPMiddleware_SkipAndMethodNormalization(t *testing.T) {
m := NewMetrics(MetricsConfig{})
h := NewHTTPMiddleware(HTTPServerConfig{
Metrics: m,
Skip: func(r *http.Request) bool { return r.URL.Path == "/skip" },
})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/skip", nil))
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("PURGE", "/x", nil))
body := scrape(t, m)
if strings.Contains(body, `method="GET"`) {
t.Error("skipped request was instrumented")
}
if !strings.Contains(body, `method="OTHER"`) {
t.Error("non-standard method not normalized to OTHER")
}
}
func TestResponseWriter_Flush(t *testing.T) {
h := NewHTTPMiddleware(HTTPServerConfig{})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f, ok := w.(http.Flusher)
if !ok {
t.Fatal("wrapped writer does not implement http.Flusher")
}
_, _ = w.Write([]byte("chunk"))
f.Flush()
}))
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
if !w.Flushed {
t.Error("Flush not propagated to the underlying writer")
}
}
func TestPatternRoute(t *testing.T) {
tests := map[string]string{
"GET /users/{id}": "/users/{id}",
"/static/": "/static/",
"example.com/": "example.com/",
"POST /x": "/x",
"": routeUnmatched,
"DELETE example.com/": "example.com/",
}
for pattern, want := range tests {
r := &http.Request{Pattern: pattern}
if got := patternRoute(r, nil); got != want {
t.Errorf("patternRoute(%q) = %q, want %q", pattern, got, want)
}
}
}
+10
View File
@@ -0,0 +1,10 @@
package obsx
import "log/slog"
// LogHandler wraps h so that records logged with a context carrying a span
// (slog.InfoContext and friends) get trace_id and span_id attributes,
// linking logs to traces.
//
// Deprecated: use NewTraceHandler, which LogHandler now calls.
func LogHandler(h slog.Handler) slog.Handler { return NewTraceHandler(h) }
+129
View File
@@ -0,0 +1,129 @@
package obsx
import (
"context"
"fmt"
"io"
"log/slog"
"os"
"strings"
"time"
"go.opentelemetry.io/otel/trace"
)
// Supported log formats for LogConfig.Format.
const (
FormatJSON = "json"
FormatText = "text"
)
// LogConfig configures the structured logger.
type LogConfig struct {
Level string // debug, info (default), warn, error; offsets like "debug-4" are accepted
Format string // FormatJSON (default) or FormatText
Output io.Writer // default: os.Stdout
AddSource bool // include file:line of the log call
}
func (c *LogConfig) defaults() {
if c.Level == "" {
c.Level = "info"
}
if c.Format == "" {
c.Format = FormatJSON
}
if c.Output == nil {
c.Output = os.Stdout
}
}
func (c LogConfig) validate() error {
if _, err := ParseLevel(c.Level); err != nil {
return err
}
switch strings.ToLower(c.Format) {
case FormatJSON, FormatText:
return nil
default:
return fmt.Errorf("obsx: unsupported log format %q (want %q or %q)", c.Format, FormatJSON, FormatText)
}
}
// NewLogger creates a slog.Logger that writes JSON (or text) records enriched
// with trace_id and span_id from the context. The returned LevelVar allows
// changing the level at runtime. An invalid level falls back to info.
//
// Use the *Context logging methods (InfoContext, ErrorContext, ...) to get
// trace correlation.
func NewLogger(cfg LogConfig) (*slog.Logger, *slog.LevelVar) {
cfg.defaults()
lv := new(slog.LevelVar)
if lvl, err := ParseLevel(cfg.Level); err == nil {
lv.Set(lvl)
}
opts := &slog.HandlerOptions{Level: lv, AddSource: cfg.AddSource}
var h slog.Handler
if strings.EqualFold(cfg.Format, FormatText) {
h = slog.NewTextHandler(cfg.Output, opts)
} else {
h = slog.NewJSONHandler(cfg.Output, opts)
}
return slog.New(NewTraceHandler(h)), lv
}
// ParseLevel parses a level name such as "debug", "INFO", "warn" or "error+2".
func ParseLevel(s string) (slog.Level, error) {
var l slog.Level
if err := l.UnmarshalText([]byte(s)); err != nil {
return 0, fmt.Errorf("obsx: invalid log level %q", s)
}
return l, nil
}
// TraceHandler is a slog.Handler middleware that adds trace_id and span_id
// attributes to every record logged with a context carrying a valid span.
type TraceHandler struct {
next slog.Handler
}
// NewTraceHandler wraps h with trace correlation.
func NewTraceHandler(h slog.Handler) *TraceHandler {
return &TraceHandler{next: h}
}
// Enabled implements slog.Handler.
func (h *TraceHandler) Enabled(ctx context.Context, level slog.Level) bool {
return h.next.Enabled(ctx, level)
}
// Handle implements slog.Handler.
func (h *TraceHandler) Handle(ctx context.Context, r slog.Record) error {
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
r = r.Clone()
r.AddAttrs(
slog.String("trace_id", sc.TraceID().String()),
slog.String("span_id", sc.SpanID().String()),
)
}
return h.next.Handle(ctx, r)
}
// WithAttrs implements slog.Handler.
func (h *TraceHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &TraceHandler{next: h.next.WithAttrs(attrs)}
}
// WithGroup implements slog.Handler.
func (h *TraceHandler) WithGroup(name string) slog.Handler {
return &TraceHandler{next: h.next.WithGroup(name)}
}
// durationAttr renders a duration as fractional milliseconds, which log
// backends can aggregate directly (slog.Duration emits integer nanoseconds
// in JSON).
func durationAttr(d time.Duration) slog.Attr {
return slog.Float64("duration_ms", float64(d.Microseconds())/1000)
}
+113
View File
@@ -0,0 +1,113 @@
package obsx
import (
"bytes"
"context"
"encoding/json"
"log/slog"
"strings"
"testing"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
func TestNewLogger_TraceCorrelation(t *testing.T) {
var buf bytes.Buffer
logger, _ := NewLogger(LogConfig{Output: &buf})
tp := sdktrace.NewTracerProvider()
ctx, span := tp.Tracer("test").Start(context.Background(), "op")
logger.InfoContext(ctx, "hello", "key", "value")
span.End()
var rec map[string]any
if err := json.Unmarshal(buf.Bytes(), &rec); err != nil {
t.Fatalf("invalid JSON log %q: %v", buf.String(), err)
}
if rec["trace_id"] != span.SpanContext().TraceID().String() {
t.Errorf("trace_id = %v, want %s", rec["trace_id"], span.SpanContext().TraceID())
}
if rec["span_id"] != span.SpanContext().SpanID().String() {
t.Errorf("span_id = %v, want %s", rec["span_id"], span.SpanContext().SpanID())
}
if rec["key"] != "value" {
t.Errorf("key = %v, want value", rec["key"])
}
}
func TestNewLogger_NoSpan(t *testing.T) {
var buf bytes.Buffer
logger, _ := NewLogger(LogConfig{Output: &buf})
logger.InfoContext(context.Background(), "hello")
if strings.Contains(buf.String(), "trace_id") {
t.Errorf("unexpected trace_id without span: %s", buf.String())
}
}
func TestNewLogger_LevelAndFormat(t *testing.T) {
var buf bytes.Buffer
logger, lv := NewLogger(LogConfig{Output: &buf, Level: "warn", Format: "text"})
logger.Info("hidden")
logger.Warn("shown")
if strings.Contains(buf.String(), "hidden") || !strings.Contains(buf.String(), "msg=shown") {
t.Errorf("unexpected text output: %q", buf.String())
}
lv.Set(slog.LevelDebug)
logger.Debug("debug now")
if !strings.Contains(buf.String(), "debug now") {
t.Errorf("level change not applied: %q", buf.String())
}
}
func TestNewLogger_WithAttrsKeepsCorrelation(t *testing.T) {
var buf bytes.Buffer
logger, _ := NewLogger(LogConfig{Output: &buf})
logger = logger.With("component", "x").WithGroup("g")
tp := sdktrace.NewTracerProvider()
ctx, span := tp.Tracer("test").Start(context.Background(), "op")
defer span.End()
logger.InfoContext(ctx, "msg")
if !strings.Contains(buf.String(), span.SpanContext().TraceID().String()) {
t.Errorf("trace id lost after With/WithGroup: %s", buf.String())
}
}
func TestParseLevel(t *testing.T) {
tests := []struct {
in string
want slog.Level
wantErr bool
}{
{"debug", slog.LevelDebug, false},
{"INFO", slog.LevelInfo, false},
{"warn", slog.LevelWarn, false},
{"error", slog.LevelError, false},
{"debug-4", slog.LevelDebug - 4, false},
{"verbose", 0, true},
}
for _, tt := range tests {
got, err := ParseLevel(tt.in)
if (err != nil) != tt.wantErr {
t.Errorf("ParseLevel(%q) error = %v, wantErr %v", tt.in, err, tt.wantErr)
}
if err == nil && got != tt.want {
t.Errorf("ParseLevel(%q) = %v, want %v", tt.in, got, tt.want)
}
}
}
func TestLogConfig_Validate(t *testing.T) {
cfg := LogConfig{Level: "info", Format: "yaml"}
if err := cfg.validate(); err == nil {
t.Error("expected error for unsupported format")
}
cfg = LogConfig{Level: "loud", Format: "json"}
if err := cfg.validate(); err == nil {
t.Error("expected error for invalid level")
}
}
+101 -16
View File
@@ -1,10 +1,15 @@
package obsx package obsx
import ( import (
"context"
"database/sql"
"errors"
"net/http" "net/http"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/otel/trace"
) )
// MetricsConfig configures the metrics factory. // MetricsConfig configures the metrics factory.
@@ -14,65 +19,145 @@ type MetricsConfig struct {
} }
// Metrics is a factory for creating Prometheus metrics with consistent naming. // Metrics is a factory for creating Prometheus metrics with consistent naming.
//
// Creating a metric that is already registered with the same name, help and
// labels returns the existing collector instead of panicking, so factories may
// be called from several places (e.g. per-handler middleware) safely.
type Metrics struct { type Metrics struct {
cfg MetricsConfig cfg MetricsConfig
registry *prometheus.Registry registry *prometheus.Registry
} }
// NewMetrics creates a new Metrics factory. // NewMetrics creates a new Metrics factory backed by an isolated registry
// pre-loaded with process and Go runtime collectors.
func NewMetrics(cfg MetricsConfig) *Metrics { func NewMetrics(cfg MetricsConfig) *Metrics {
reg := prometheus.NewRegistry() reg := prometheus.NewRegistry()
reg.MustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{})) reg.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
reg.MustRegister(prometheus.NewGoCollector()) reg.MustRegister(collectors.NewGoCollector())
return &Metrics{cfg: cfg, registry: reg} return &Metrics{cfg: cfg, registry: reg}
} }
// Sub returns a factory sharing the same registry and namespace but using the
// given subsystem, e.g. m.Sub("db").Counter("queries_total", ...) produces
// "<namespace>_db_queries_total".
func (m *Metrics) Sub(subsystem string) *Metrics {
return &Metrics{
cfg: MetricsConfig{Namespace: m.cfg.Namespace, Subsystem: subsystem},
registry: m.registry,
}
}
// base returns a factory without namespace/subsystem sharing the registry.
// Built-in instrumentation uses it so that standard metric names are identical
// across all services.
func (m *Metrics) base() *Metrics {
return &Metrics{registry: m.registry}
}
// Counter creates and registers a new CounterVec. // Counter creates and registers a new CounterVec.
func (m *Metrics) Counter(name, help string, labels ...string) *prometheus.CounterVec { func (m *Metrics) Counter(name, help string, labels ...string) *prometheus.CounterVec {
c := prometheus.NewCounterVec(prometheus.CounterOpts{ return register(m.registry, prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: m.cfg.Namespace, Namespace: m.cfg.Namespace,
Subsystem: m.cfg.Subsystem, Subsystem: m.cfg.Subsystem,
Name: name, Name: name,
Help: help, Help: help,
}, labels) }, labels))
m.registry.MustRegister(c)
return c
} }
// Histogram creates and registers a new HistogramVec. // Histogram creates and registers a new HistogramVec.
// nil buckets default to prometheus.DefBuckets.
func (m *Metrics) Histogram(name, help string, buckets []float64, labels ...string) *prometheus.HistogramVec { func (m *Metrics) Histogram(name, help string, buckets []float64, labels ...string) *prometheus.HistogramVec {
if buckets == nil { if buckets == nil {
buckets = prometheus.DefBuckets buckets = prometheus.DefBuckets
} }
h := prometheus.NewHistogramVec(prometheus.HistogramOpts{ return register(m.registry, prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: m.cfg.Namespace, Namespace: m.cfg.Namespace,
Subsystem: m.cfg.Subsystem, Subsystem: m.cfg.Subsystem,
Name: name, Name: name,
Help: help, Help: help,
Buckets: buckets, Buckets: buckets,
}, labels) }, labels))
m.registry.MustRegister(h)
return h
} }
// Gauge creates and registers a new GaugeVec. // Gauge creates and registers a new GaugeVec.
func (m *Metrics) Gauge(name, help string, labels ...string) *prometheus.GaugeVec { func (m *Metrics) Gauge(name, help string, labels ...string) *prometheus.GaugeVec {
g := prometheus.NewGaugeVec(prometheus.GaugeOpts{ return register(m.registry, prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: m.cfg.Namespace, Namespace: m.cfg.Namespace,
Subsystem: m.cfg.Subsystem, Subsystem: m.cfg.Subsystem,
Name: name, Name: name,
Help: help, Help: help,
}, labels) }, labels))
m.registry.MustRegister(g) }
return g
// GaugeFunc registers a gauge whose value is computed by fn on every scrape,
// e.g. queue length or cache size. Unlike Counter and friends it panics when
// the name is already registered: a second fn would otherwise be ignored.
func (m *Metrics) GaugeFunc(name, help string, fn func() float64) {
m.registry.MustRegister(prometheus.NewGaugeFunc(prometheus.GaugeOpts{
Namespace: m.cfg.Namespace,
Subsystem: m.cfg.Subsystem,
Name: name,
Help: help,
}, fn))
}
// CounterFunc registers a counter whose value is computed by fn on every
// scrape. fn must return monotonically increasing values. It panics when the
// name is already registered.
func (m *Metrics) CounterFunc(name, help string, fn func() float64) {
m.registry.MustRegister(prometheus.NewCounterFunc(prometheus.CounterOpts{
Namespace: m.cfg.Namespace,
Subsystem: m.cfg.Subsystem,
Name: name,
Help: help,
}, fn))
}
// RegisterDBStats exports database/sql connection pool statistics
// (go_sql_* metrics) labeled with db_name=name. It panics when name is
// already registered: stats of a second pool would otherwise be dropped.
func (m *Metrics) RegisterDBStats(db *sql.DB, name string) {
m.registry.MustRegister(collectors.NewDBStatsCollector(db, name))
} }
// Handler returns an http.Handler for the /metrics endpoint. // Handler returns an http.Handler for the /metrics endpoint.
// OpenMetrics format is negotiated when requested, which exposes trace
// exemplars attached by the built-in instrumentation.
func (m *Metrics) Handler() http.Handler { func (m *Metrics) Handler() http.Handler {
return promhttp.HandlerFor(m.registry, promhttp.HandlerOpts{}) return promhttp.HandlerFor(m.registry, promhttp.HandlerOpts{
EnableOpenMetrics: true,
})
} }
// Registry returns the underlying Prometheus registry. // Registry returns the underlying Prometheus registry.
func (m *Metrics) Registry() *prometheus.Registry { func (m *Metrics) Registry() *prometheus.Registry {
return m.registry return m.registry
} }
// register registers c, returning the already registered collector when an
// identical one exists. It panics on any other registration error, matching
// MustRegister semantics.
func register[T prometheus.Collector](reg prometheus.Registerer, c T) T {
if err := reg.Register(c); err != nil {
var are prometheus.AlreadyRegisteredError
if errors.As(err, &are) {
if existing, ok := are.ExistingCollector.(T); ok {
return existing
}
}
panic(err)
}
return c
}
// observe records v, attaching the trace ID from ctx as an exemplar when the
// span is sampled.
func observe(ctx context.Context, o prometheus.Observer, v float64) {
if sc := trace.SpanContextFromContext(ctx); sc.IsSampled() {
if eo, ok := o.(prometheus.ExemplarObserver); ok {
eo.ObserveWithExemplar(v, prometheus.Labels{"trace_id": sc.TraceID().String()})
return
}
}
o.Observe(v)
}
+77
View File
@@ -1,11 +1,17 @@
package obsx package obsx
import ( import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"io" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
"testing" "testing"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
) )
func TestMetrics_Counter(t *testing.T) { func TestMetrics_Counter(t *testing.T) {
@@ -62,3 +68,74 @@ func scrape(t *testing.T, m *Metrics) string {
body, _ := io.ReadAll(w.Body) body, _ := io.ReadAll(w.Body)
return string(body) return string(body)
} }
func TestMetrics_Sub(t *testing.T) {
m := NewMetrics(MetricsConfig{Namespace: "app"})
m.Sub("db").Counter("queries_total", "Queries").WithLabelValues().Inc()
if !strings.Contains(scrape(t, m), "app_db_queries_total 1") {
t.Error("Sub factory must share the registry and namespace")
}
}
func TestMetrics_IdempotentRegistration(t *testing.T) {
m := NewMetrics(MetricsConfig{})
a := m.Counter("events_total", "Events", "kind")
b := m.Counter("events_total", "Events", "kind")
if a != b {
t.Error("registering an identical metric must return the existing collector")
}
defer func() {
if recover() == nil {
t.Error("conflicting registration must panic")
}
}()
m.Counter("events_total", "Events", "other_label")
}
func TestMetrics_Funcs(t *testing.T) {
m := NewMetrics(MetricsConfig{Namespace: "q"})
m.GaugeFunc("depth", "Queue depth", func() float64 { return 7 })
m.CounterFunc("processed_total", "Processed", func() float64 { return 3 })
body := scrape(t, m)
if !strings.Contains(body, "q_depth 7") || !strings.Contains(body, "q_processed_total 3") {
t.Errorf("func metrics missing:\n%s", body)
}
}
func TestMetrics_DBStats(t *testing.T) {
m := NewMetrics(MetricsConfig{})
// sql.OpenDB does not dial, so no real database is needed.
db := sql.OpenDB(nopConnector{})
defer db.Close()
m.RegisterDBStats(db, "main")
if !strings.Contains(scrape(t, m), `go_sql_max_open_connections{db_name="main"}`) {
t.Error("db stats missing")
}
}
func TestMetrics_Exemplars(t *testing.T) {
m := NewMetrics(MetricsConfig{})
h := m.Histogram("latency_seconds", "Latency", nil)
tp := sdktrace.NewTracerProvider()
ctx, span := tp.Tracer("t").Start(context.Background(), "op")
observe(ctx, h.WithLabelValues(), 0.2)
span.End()
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/metrics", nil)
r.Header.Set("Accept", "application/openmetrics-text; version=1.0.0")
m.Handler().ServeHTTP(w, r)
if !strings.Contains(w.Body.String(), `# {trace_id="`+span.SpanContext().TraceID().String()+`"} 0.2`) {
t.Errorf("exemplar missing from OpenMetrics output:\n%s", w.Body.String())
}
}
type nopConnector struct{}
func (nopConnector) Connect(context.Context) (driver.Conn, error) { return nil, errors.New("no db") }
func (nopConnector) Driver() driver.Driver { return nil }
+296
View File
@@ -0,0 +1,296 @@
package obsx
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
)
// Observer is the single entry point wiring logging, tracing, metrics, health
// checks and the admin server for a service. Create it once in main with New
// and pass it (or its components) to the rest of the application.
type Observer struct {
cfg Config
info BuildInfo
logger *slog.Logger
level *slog.LevelVar
tp trace.TracerProvider
tracer trace.Tracer
metrics *Metrics
health *Health
ops *prometheus.HistogramVec
admin *http.Server
adminAddr string
shutdownTracer func(context.Context) error
shutdownOnce sync.Once
shutdownErr error
}
// New sets up observability for a service:
//
// - a JSON slog.Logger with service attributes and trace correlation,
// installed as slog.Default;
// - an OpenTelemetry tracer provider with OTLP export and W3C propagation,
// installed as the global provider;
// - a Prometheus registry with Go/process collectors and a
// service_build_info metric;
// - health checks and, when Admin.Addr is set, the admin HTTP server.
//
// Call Shutdown on exit to flush spans and stop the admin server.
func New(ctx context.Context, cfg Config) (*Observer, error) {
cfg.defaults()
if err := cfg.Logging.validate(); err != nil {
return nil, err
}
start := time.Now()
o := &Observer{cfg: cfg, info: newBuildInfo(cfg, start)}
logger, level := NewLogger(cfg.Logging)
o.logger = logger.With(serviceLogAttrs(cfg)...)
o.level = level
tp, shutdown, err := newTracerProvider(ctx, cfg.Tracing)
if err != nil {
return nil, err
}
o.tp = tp
o.tracer = tp.Tracer(cfg.ServiceName)
o.shutdownTracer = shutdown
o.metrics = NewMetrics(cfg.Metrics)
base := o.metrics.base()
base.Gauge("service_build_info",
"Build information of the service; the value is always 1.",
"service", "version", "environment", "revision", "go_version",
).WithLabelValues(o.info.Service, o.info.Version, o.info.Environment, o.info.Revision, o.info.GoVersion).Set(1)
o.ops = base.Histogram("operation_duration_seconds",
"Duration of operations tracked with Observer.Track.", nil, "operation", "status")
healthCfg := cfg.Health
healthCfg.Metrics = o.metrics
o.health = NewHealth(healthCfg)
if cfg.Admin.Addr != "" {
if err := o.startAdmin(cfg.Admin.Addr); err != nil {
_ = shutdown(ctx)
return nil, err
}
}
// Install globals only once nothing can fail anymore.
slog.SetDefault(o.logger)
setGlobalTracing(tp)
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(err error) {
o.logger.Warn("opentelemetry error", slog.Any("error", err))
}))
return o, nil
}
func serviceLogAttrs(cfg Config) []any {
attrs := []any{slog.String("service", cfg.ServiceName)}
if cfg.ServiceVersion != "" {
attrs = append(attrs, slog.String("version", cfg.ServiceVersion))
}
if cfg.Environment != "" {
attrs = append(attrs, slog.String("env", cfg.Environment))
}
return attrs
}
func (o *Observer) startAdmin(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return fmt.Errorf("obsx: admin server listen on %s: %w", addr, err)
}
o.adminAddr = ln.Addr().String()
o.admin = &http.Server{
Handler: o.AdminHandler(),
ReadHeaderTimeout: 5 * time.Second,
ErrorLog: slog.NewLogLogger(o.logger.Handler(), slog.LevelWarn),
}
go func() {
if err := o.admin.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
o.logger.Error("admin server stopped", slog.Any("error", err))
}
}()
o.logger.Info("admin server started", slog.String("addr", o.adminAddr))
return nil
}
// Logger returns the service logger (also installed as slog.Default).
func (o *Observer) Logger() *slog.Logger { return o.logger }
// LogLevel returns the variable controlling the log level at runtime.
func (o *Observer) LogLevel() *slog.LevelVar { return o.level }
// Metrics returns the metrics factory scoped by Config.Metrics.
func (o *Observer) Metrics() *Metrics { return o.metrics }
// Health returns the health checks registry.
func (o *Observer) Health() *Health { return o.health }
// TracerProvider returns the tracer provider (also installed globally).
func (o *Observer) TracerProvider() trace.TracerProvider { return o.tp }
// Tracer returns a tracer named after the service.
func (o *Observer) Tracer() trace.Tracer { return o.tracer }
// BuildInfo returns information about the running service.
func (o *Observer) BuildInfo() BuildInfo {
info := o.info
info.Uptime = time.Since(info.StartTime).Round(time.Second).String()
return info
}
// AdminAddr returns the address the admin server listens on, or "" if it is
// not running. Useful with Admin.Addr ":0".
func (o *Observer) AdminAddr() string { return o.adminAddr }
// Start starts a span with the service tracer.
func (o *Observer) Start(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
return o.tracer.Start(ctx, name, opts...)
}
// Track runs fn as a named operation (database query, cache call, message
// handling, background job...) with a span and the
// operation_duration_seconds{operation,status} histogram, where status is
// "ok" or "error". Use a low-cardinality operation name such as "db.get_user".
func (o *Observer) Track(ctx context.Context, operation string, fn func(ctx context.Context) error) error {
start := time.Now()
ctx, span := o.tracer.Start(ctx, operation, trace.WithAttributes(attribute.String("operation", operation)))
defer span.End()
statusLabel := "ok"
defer func() {
if rec := recover(); rec != nil {
failSpan(span, fmt.Errorf("panic: %v", rec))
observe(ctx, o.ops.WithLabelValues(operation, "error"), time.Since(start).Seconds())
panic(rec)
}
observe(ctx, o.ops.WithLabelValues(operation, statusLabel), time.Since(start).Seconds())
}()
err := fn(ctx)
if err != nil {
statusLabel = "error"
failSpan(span, err)
}
return err
}
func (o *Observer) accessLogger() *slog.Logger {
if o.cfg.DisableAccessLog {
return nil
}
return o.logger
}
// HTTPMiddleware instruments an HTTP handler with tracing, metrics and access
// logs, tuned by Config.HTTP. It can wrap a handler directly or be used as
// router middleware:
//
// http.ListenAndServe(":8080", o.HTTPMiddleware(mux))
// r.Use(o.HTTPMiddleware) // chi and similar routers: set Config.HTTP.RouteFunc
func (o *Observer) HTTPMiddleware(next http.Handler) http.Handler {
cfg := o.cfg.HTTP
if cfg.Metrics == nil {
cfg.Metrics = o.metrics
}
if cfg.Logger == nil {
cfg.Logger = o.accessLogger()
}
if cfg.TracerProvider == nil {
cfg.TracerProvider = o.tp
}
return NewHTTPMiddleware(cfg)(next)
}
// HTTPTransport wraps base (http.DefaultTransport when nil) with client
// tracing, context propagation and metrics, tuned by Config.HTTPClient.
func (o *Observer) HTTPTransport(base http.RoundTripper) http.RoundTripper {
cfg := o.cfg.HTTPClient
if cfg.Metrics == nil {
cfg.Metrics = o.metrics
}
if cfg.TracerProvider == nil {
cfg.TracerProvider = o.tp
}
return NewHTTPTransport(base, cfg)
}
// HTTPClient returns an *http.Client with an instrumented transport.
func (o *Observer) HTTPClient() *http.Client {
return &http.Client{Transport: o.HTTPTransport(nil)}
}
// GRPCInterceptors returns instrumented gRPC interceptors bound to this
// Observer, tuned by Config.GRPC. Health-check calls are never instrumented.
func (o *Observer) GRPCInterceptors() *GRPCInterceptors {
cfg := o.cfg.GRPC
if cfg.Metrics == nil {
cfg.Metrics = o.metrics
}
if cfg.Logger == nil {
cfg.Logger = o.accessLogger()
}
if cfg.TracerProvider == nil {
cfg.TracerProvider = o.tp
}
skip := cfg.Skip
cfg.Skip = func(fullMethod string) bool {
return strings.HasPrefix(fullMethod, "/grpc.health.v1.Health/") || skip != nil && skip(fullMethod)
}
return NewGRPCInterceptors(cfg)
}
// GRPCServerOptions returns grpc.NewServer options with instrumentation.
func (o *Observer) GRPCServerOptions() []grpc.ServerOption {
return o.GRPCInterceptors().ServerOptions()
}
// GRPCDialOptions returns grpc.NewClient options with instrumentation.
func (o *Observer) GRPCDialOptions() []grpc.DialOption {
return o.GRPCInterceptors().DialOptions()
}
// adminShutdownTimeout bounds the graceful stop of the admin server; it
// serves only short internal requests, so lingering connections are closed.
const adminShutdownTimeout = time.Second
// Shutdown marks the service not ready, flushes pending spans and stops the
// admin server. It is safe to call multiple times.
func (o *Observer) Shutdown(ctx context.Context) error {
o.shutdownOnce.Do(func() {
o.health.SetReady(false)
var errs []error
if err := o.shutdownTracer(ctx); err != nil {
errs = append(errs, fmt.Errorf("obsx: tracer shutdown: %w", err))
}
if o.admin != nil {
adminCtx, cancel := context.WithTimeout(ctx, adminShutdownTimeout)
if o.admin.Shutdown(adminCtx) != nil {
if err := o.admin.Close(); err != nil {
errs = append(errs, fmt.Errorf("obsx: admin server close: %w", err))
}
}
cancel()
}
o.shutdownErr = errors.Join(errs...)
})
return o.shutdownErr
}
+334
View File
@@ -0,0 +1,334 @@
package obsx
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
)
// newTestObserver creates an Observer exporting spans to memory and logging
// to a buffer. Global state touched by New is restored on cleanup.
func newTestObserver(t *testing.T, cfg Config) (*Observer, *tracetest.InMemoryExporter, *bytes.Buffer) {
t.Helper()
prevTP, prevProp, prevLog := otel.GetTracerProvider(), otel.GetTextMapPropagator(), slog.Default()
t.Cleanup(func() {
otel.SetTracerProvider(prevTP)
otel.SetTextMapPropagator(prevProp)
slog.SetDefault(prevLog)
})
exp := tracetest.NewInMemoryExporter()
var logs bytes.Buffer
if cfg.ServiceName == "" {
cfg.ServiceName = "orders"
}
cfg.Tracing.Exporter = exp
cfg.Logging.Output = &logs
o, err := New(context.Background(), cfg)
if err != nil {
t.Fatalf("New: %v", err)
}
t.Cleanup(func() { _ = o.Shutdown(context.Background()) })
return o, exp, &logs
}
// flushSpans exports spans buffered by the batch span processor.
func flushSpans(t *testing.T, o *Observer, exp *tracetest.InMemoryExporter) tracetest.SpanStubs {
t.Helper()
if err := o.TracerProvider().(*sdktrace.TracerProvider).ForceFlush(context.Background()); err != nil {
t.Fatal(err)
}
return exp.GetSpans()
}
func TestNew_Defaults(t *testing.T) {
o, _, logs := newTestObserver(t, Config{ServiceVersion: "1.2.3", Environment: "test"})
o.Logger().Info("ready")
var rec map[string]any
if err := json.Unmarshal(logs.Bytes(), &rec); err != nil {
t.Fatalf("invalid log %q: %v", logs.String(), err)
}
if rec["service"] != "orders" || rec["version"] != "1.2.3" || rec["env"] != "test" {
t.Errorf("service attributes missing from log: %v", rec)
}
if otel.GetTracerProvider() != o.TracerProvider() {
t.Error("tracer provider not installed globally")
}
body := scrape(t, o.Metrics())
if !strings.Contains(body, `service_build_info{`) || !strings.Contains(body, `service="orders"`) || !strings.Contains(body, `version="1.2.3"`) {
t.Errorf("service_build_info missing:\n%s", body)
}
if !strings.Contains(body, "go_goroutines") {
t.Error("Go runtime metrics missing")
}
if o.AdminAddr() != "" {
t.Error("admin server must not start without Admin.Addr")
}
}
func TestNew_InvalidConfig(t *testing.T) {
if _, err := New(context.Background(), Config{Logging: LogConfig{Level: "loud"}}); err == nil {
t.Error("expected error for invalid log level")
}
if _, err := New(context.Background(), Config{Tracing: TracerConfig{Endpoint: "localhost:4317", Protocol: "zipkin"}}); err == nil {
t.Error("expected error for unsupported protocol")
}
}
func TestObserver_EndToEndHTTP(t *testing.T) {
o, exp, logs := newTestObserver(t, Config{})
// Downstream service called through the instrumented client.
downstream := httptest.NewServer(o.HTTPMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
o.Logger().InfoContext(r.Context(), "downstream handled")
})))
defer downstream.Close()
client := o.HTTPClient()
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 nil })
if err != nil {
t.Error(err)
}
req, _ := http.NewRequestWithContext(r.Context(), "GET", downstream.URL, nil)
resp, err := client.Do(req)
if err != nil {
t.Error(err)
return
}
resp.Body.Close()
})
srv := httptest.NewServer(o.HTTPMiddleware(mux))
defer srv.Close()
resp, err := http.Get(srv.URL + "/orders/42")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
// All spans belong to one trace: server -> track + client -> downstream server.
spans := flushSpans(t, o, exp)
if len(spans) != 4 {
t.Fatalf("got %d spans, want 4", len(spans))
}
traceID := spans[0].SpanContext.TraceID()
for _, s := range spans {
if s.SpanContext.TraceID() != traceID {
t.Errorf("span %q is in a different trace", s.Name)
}
}
// Downstream log line carries the shared trace ID.
if !strings.Contains(logs.String(), `"msg":"downstream handled"`) || !strings.Contains(logs.String(), traceID.String()) {
t.Errorf("log correlation broken:\n%s", logs.String())
}
body := scrape(t, o.Metrics())
for _, want := range []string{
`http_server_requests_total{code="200",method="GET",route="/orders/{id}"} 1`,
`http_client_requests_total{code="200",`,
`operation_duration_seconds_count{operation="db.get_order",status="ok"} 1`,
} {
if !strings.Contains(body, want) {
t.Errorf("metrics missing %q", want)
}
}
}
func TestObserver_TrackError(t *testing.T) {
o, exp, _ := newTestObserver(t, Config{})
want := errors.New("not found")
err := o.Track(context.Background(), "db.query", func(ctx context.Context) error { return want })
if !errors.Is(err, want) {
t.Fatalf("Track returned %v", err)
}
spans := flushSpans(t, o, exp)
if len(spans) != 1 || spans[0].Name != "db.query" || spans[0].Status.Code != codes.Error {
t.Errorf("unexpected spans: %+v", spans)
}
if !strings.Contains(scrape(t, o.Metrics()), `operation_duration_seconds_count{operation="db.query",status="error"} 1`) {
t.Error("error status not recorded")
}
func() {
defer func() { _ = recover() }()
_ = o.Track(context.Background(), "job", func(ctx context.Context) error { panic("boom") })
}()
if !strings.Contains(scrape(t, o.Metrics()), `operation_duration_seconds_count{operation="job",status="error"} 1`) {
t.Error("panic not recorded as error")
}
}
func TestObserver_AdminServer(t *testing.T) {
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{Addr: "127.0.0.1:0", EnablePprof: true}})
base := "http://" + o.AdminAddr()
get := func(path string) (int, string) {
t.Helper()
resp, err := http.Get(base + path)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, string(b)
}
for path, want := range map[string]string{
"/metrics": "service_build_info",
"/healthz": `"status": "ok"`,
"/livez": `"status": "ok"`,
"/readyz": `"status": "ok"`,
"/buildinfo": `"service": "orders"`,
"/loglevel": `"level": "INFO"`,
"/debug/pprof/": "goroutine",
} {
code, body := get(path)
if code != http.StatusOK || !strings.Contains(body, want) {
t.Errorf("GET %s = %d, want 200 containing %q:\n%s", path, code, want, body)
}
}
req, _ := http.NewRequest("PUT", base+"/loglevel?level=debug", nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK || !o.Logger().Enabled(context.Background(), -4) {
t.Errorf("log level not changed: %d", resp.StatusCode)
}
req, _ = http.NewRequest("PUT", base+"/loglevel", strings.NewReader("nonsense"))
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("invalid level code = %d, want 400", resp.StatusCode)
}
o.Health().AddReadinessCheck("db", func(ctx context.Context) error { return errors.New("down") })
if code, _ := get("/readyz"); code != http.StatusServiceUnavailable {
t.Errorf("/readyz = %d, want 503", code)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := o.Shutdown(ctx); err != nil {
t.Fatalf("Shutdown: %v", err)
}
if _, err := http.Get(base + "/healthz"); err == nil {
t.Error("admin server still serving after Shutdown")
}
if err := o.Shutdown(ctx); err != nil {
t.Errorf("second Shutdown: %v", err)
}
}
func TestObserver_AdminPprofOffByDefault(t *testing.T) {
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{}})
w := httptest.NewRecorder()
o.AdminHandler().ServeHTTP(w, httptest.NewRequest("GET", "/debug/pprof/", nil))
if w.Code != http.StatusNotFound {
t.Errorf("pprof code = %d, want 404", w.Code)
}
}
func TestObserver_AdminAddrInUse(t *testing.T) {
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{Addr: "127.0.0.1:0"}})
_, err := New(context.Background(), Config{
Admin: AdminConfig{Addr: o.AdminAddr()},
Logging: LogConfig{Output: io.Discard},
})
if err == nil {
t.Error("expected listen error for busy address")
}
}
func TestObserver_ShutdownMarksNotReady(t *testing.T) {
o, _, _ := newTestObserver(t, Config{})
if err := o.Shutdown(context.Background()); err != nil {
t.Fatal(err)
}
if o.Health().CheckReadiness(context.Background()).Healthy() {
t.Error("service must not be ready after Shutdown")
}
}
func TestObserver_AccessLogDisabled(t *testing.T) {
o, _, logs := newTestObserver(t, Config{DisableAccessLog: true})
o.HTTPMiddleware(http.NotFoundHandler()).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
if strings.Contains(logs.String(), "http request") {
t.Errorf("access log written although disabled: %s", logs.String())
}
}
func TestConfig_WithEnv(t *testing.T) {
t.Setenv("OTEL_SERVICE_NAME", "from-otel")
t.Setenv("OBSX_SERVICE_NAME", "from-obsx")
t.Setenv("OBSX_ENVIRONMENT", "staging")
t.Setenv("OBSX_LOG_LEVEL", "debug")
t.Setenv("OBSX_TRACING_SAMPLER", "0.25")
t.Setenv("OBSX_TRACING_DISABLED", "true")
t.Setenv("OBSX_TRACING_INSECURE", "true")
t.Setenv("OBSX_ADMIN_ENABLE_PPROF", "true")
t.Setenv("OBSX_HEALTH_TIMEOUT", "3s")
t.Setenv("OBSX_ADMIN_ADDR", ":9999")
t.Setenv("OBSX_DISABLE_ACCESS_LOG", "not-a-bool")
cfg := Config{ServiceName: "from-code", Logging: LogConfig{Format: "text"}}.WithEnv()
if cfg.ServiceName != "from-obsx" {
t.Errorf("ServiceName = %q", cfg.ServiceName)
}
if cfg.Environment != "staging" || cfg.Logging.Level != "debug" || cfg.Logging.Format != "text" {
t.Errorf("unexpected config: %+v", cfg)
}
if cfg.Tracing.Sampler != 0.25 || !cfg.Tracing.Disabled || !cfg.Tracing.Insecure || !cfg.Admin.EnablePprof {
t.Errorf("unexpected tracing config: %+v", cfg.Tracing)
}
if cfg.Health.Timeout != 3*time.Second || cfg.Admin.Addr != ":9999" {
t.Errorf("unexpected health/admin config: %+v %+v", cfg.Health, cfg.Admin)
}
if cfg.DisableAccessLog {
t.Error("malformed bool must be ignored")
}
}
func TestConfig_DefaultsInheritIdentity(t *testing.T) {
cfg := Config{ServiceName: "svc", ServiceVersion: "v1", Environment: "prod"}
cfg.defaults()
if cfg.Tracing.ServiceName != "svc" || cfg.Tracing.ServiceVersion != "v1" || cfg.Tracing.Environment != "prod" {
t.Errorf("tracing identity not inherited: %+v", cfg.Tracing)
}
cfg = Config{}
cfg.defaults()
if cfg.ServiceName == "" {
t.Error("ServiceName must default to the executable name")
}
}
+216 -26
View File
@@ -1,67 +1,257 @@
package obsx package obsx
import ( import (
"cmp"
"context" "context"
"crypto/tls"
"fmt"
"os"
"strings"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.26.0" semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/noop"
"google.golang.org/grpc/credentials"
)
// Supported OTLP protocols for TracerConfig.Protocol.
const (
ProtocolGRPC = "grpc"
ProtocolHTTP = "http"
) )
// TracerConfig configures the OpenTelemetry tracer. // TracerConfig configures the OpenTelemetry tracer.
type TracerConfig struct { type TracerConfig struct {
ServiceName string ServiceName string
ServiceVersion string ServiceVersion string
Endpoint string // OTLP gRPC endpoint, e.g. "localhost:4317" // Environment is the deployment.environment.name resource attribute, e.g. "production".
Sampler float64 // sampling ratio, default: 1.0 (sample everything) Environment string
// Endpoint is the OTLP collector endpoint: "host:port" or a URL
// ("https://collector:4318"). When empty, the standard
// OTEL_EXPORTER_OTLP_ENDPOINT / OTEL_EXPORTER_OTLP_TRACES_ENDPOINT
// variables are used; if those are unset too, spans are still created and
// propagated (trace IDs appear in logs) but not exported.
Endpoint string
// Protocol is ProtocolGRPC or ProtocolHTTP. When empty,
// OTEL_EXPORTER_OTLP_TRACES_PROTOCOL / OTEL_EXPORTER_OTLP_PROTOCOL apply,
// then ProtocolGRPC.
Protocol string
// Insecure disables TLS for the OTLP connection (local collectors, sidecars).
Insecure bool
// TLS is a custom TLS configuration for the OTLP connection; nil uses the
// system defaults. Ignored when Insecure is set.
TLS *tls.Config
// Headers are sent with every export request, e.g. for authentication.
Headers map[string]string
// Sampler is the ratio of root traces to sample, default: 1.0 (everything).
// Child spans always follow the decision of their parent.
Sampler float64
// Disabled installs a no-op provider: no spans are recorded or propagated.
Disabled bool
// Attributes are extra resource attributes.
Attributes []attribute.KeyValue
// Exporter overrides the OTLP exporter (e.g. stdouttrace or an in-memory
// exporter in tests). Endpoint, Protocol, Insecure, TLS and Headers are ignored.
Exporter sdktrace.SpanExporter
} }
func (c *TracerConfig) defaults() { func (c *TracerConfig) defaults() {
if c.Sampler <= 0 { if c.Sampler <= 0 {
c.Sampler = 1.0 c.Sampler = 1.0
} }
if c.Protocol == "" {
c.Protocol = cmp.Or(os.Getenv("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"), os.Getenv("OTEL_EXPORTER_OTLP_PROTOCOL"), ProtocolGRPC)
}
} }
// SetupTracer initializes an OpenTelemetry tracer provider with OTLP gRPC exporter. // SetupTracer initializes an OpenTelemetry tracer provider with an OTLP
// Returns a shutdown function that must be called on application exit. // exporter and installs it, together with W3C TraceContext and Baggage
// propagators, as the OpenTelemetry globals.
// Returns a shutdown function that must be called on application exit to
// flush pending spans.
func SetupTracer(ctx context.Context, cfg TracerConfig) (shutdown func(context.Context) error, err error) { func SetupTracer(ctx context.Context, cfg TracerConfig) (shutdown func(context.Context) error, err error) {
tp, shutdown, err := newTracerProvider(ctx, cfg)
if err != nil {
return nil, err
}
setGlobalTracing(tp)
return shutdown, nil
}
func setGlobalTracing(tp trace.TracerProvider) {
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{},
))
}
func newTracerProvider(ctx context.Context, cfg TracerConfig) (trace.TracerProvider, func(context.Context) error, error) {
cfg.defaults() cfg.defaults()
exporter, err := otlptracegrpc.New(ctx, if cfg.Disabled {
otlptracegrpc.WithEndpoint(cfg.Endpoint), return noop.NewTracerProvider(), func(context.Context) error { return nil }, nil
otlptracegrpc.WithInsecure(),
)
if err != nil {
return nil, err
} }
attrs := []resource.Option{ exporter, err := newExporter(ctx, cfg)
resource.WithAttributes(semconv.ServiceName(cfg.ServiceName)), if err != nil {
return nil, nil, fmt.Errorf("obsx: create trace exporter: %w", err)
}
res, err := newResource(ctx, cfg)
if err != nil {
if exporter != nil {
_ = exporter.Shutdown(ctx)
}
return nil, nil, fmt.Errorf("obsx: create trace resource: %w", err)
}
opts := []sdktrace.TracerProviderOption{
sdktrace.WithResource(res),
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(cfg.Sampler))),
}
if exporter != nil {
opts = append(opts, sdktrace.WithBatcher(exporter))
}
tp := sdktrace.NewTracerProvider(opts...)
return tp, tp.Shutdown, nil
}
// newExporter returns nil (and no error) when no endpoint is configured.
func newExporter(ctx context.Context, cfg TracerConfig) (sdktrace.SpanExporter, error) {
if cfg.Exporter != nil {
return cfg.Exporter, nil
}
if cfg.Endpoint == "" &&
os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") == "" &&
os.Getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") == "" {
return nil, nil
}
isURL := strings.Contains(cfg.Endpoint, "://")
switch cfg.Protocol {
case ProtocolGRPC:
var opts []otlptracegrpc.Option
switch {
case isURL:
opts = append(opts, otlptracegrpc.WithEndpointURL(cfg.Endpoint))
case cfg.Endpoint != "":
opts = append(opts, otlptracegrpc.WithEndpoint(cfg.Endpoint))
}
switch {
case cfg.Insecure:
opts = append(opts, otlptracegrpc.WithInsecure())
case cfg.TLS != nil:
opts = append(opts, otlptracegrpc.WithTLSCredentials(credentials.NewTLS(cfg.TLS)))
}
if len(cfg.Headers) > 0 {
opts = append(opts, otlptracegrpc.WithHeaders(cfg.Headers))
}
return otlptracegrpc.New(ctx, opts...)
case ProtocolHTTP, "http/protobuf":
var opts []otlptracehttp.Option
switch {
case isURL:
opts = append(opts, otlptracehttp.WithEndpointURL(cfg.Endpoint))
case cfg.Endpoint != "":
opts = append(opts, otlptracehttp.WithEndpoint(cfg.Endpoint))
}
switch {
case cfg.Insecure:
opts = append(opts, otlptracehttp.WithInsecure())
case cfg.TLS != nil:
opts = append(opts, otlptracehttp.WithTLSClientConfig(cfg.TLS))
}
if len(cfg.Headers) > 0 {
opts = append(opts, otlptracehttp.WithHeaders(cfg.Headers))
}
return otlptracehttp.New(ctx, opts...)
default:
return nil, fmt.Errorf("unsupported OTLP protocol %q (want %q or %q)", cfg.Protocol, ProtocolGRPC, ProtocolHTTP)
}
}
func newResource(ctx context.Context, cfg TracerConfig) (*resource.Resource, error) {
var attrs []attribute.KeyValue
if cfg.ServiceName != "" {
attrs = append(attrs, semconv.ServiceName(cfg.ServiceName))
} }
if cfg.ServiceVersion != "" { if cfg.ServiceVersion != "" {
attrs = append(attrs, resource.WithAttributes(semconv.ServiceVersion(cfg.ServiceVersion))) attrs = append(attrs, semconv.ServiceVersion(cfg.ServiceVersion))
} }
if cfg.Environment != "" {
attrs = append(attrs, attribute.String("deployment.environment.name", cfg.Environment))
}
if host, err := os.Hostname(); err == nil {
attrs = append(attrs, semconv.ServiceInstanceID(host))
}
attrs = append(attrs, cfg.Attributes...)
res, err := resource.New(ctx, attrs...) // Later options win: explicit configuration overrides OTEL_RESOURCE_ATTRIBUTES.
if err != nil { res, err := resource.New(ctx,
resource.WithTelemetrySDK(),
resource.WithHost(),
resource.WithFromEnv(),
resource.WithAttributes(attrs...),
)
if res == nil {
return nil, err return nil, err
} }
// Partial detector failures still yield a usable resource.
tp := sdktrace.NewTracerProvider( return res, nil
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(res),
sdktrace.WithSampler(sdktrace.TraceIDRatioBased(cfg.Sampler)),
)
otel.SetTracerProvider(tp)
return tp.Shutdown, nil
} }
const tracerName = "git.codelab.vc/pkg/obsx"
// StartSpan starts a new span using the global tracer provider. // StartSpan starts a new span using the global tracer provider.
func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) { func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
return otel.Tracer("obsx").Start(ctx, name, opts...) return otel.Tracer(tracerName).Start(ctx, name, opts...)
}
// Trace runs fn inside a new span. A non-nil error returned by fn is recorded
// on the span and the span status is set to Error.
func Trace(ctx context.Context, name string, fn func(ctx context.Context) error) error {
ctx, span := StartSpan(ctx, name)
defer span.End()
err := fn(ctx)
if err != nil {
failSpan(span, err)
}
return err
}
// RecordError records err on the span stored in ctx and marks the span as
// failed. It is a no-op when err is nil or ctx carries no recording span.
func RecordError(ctx context.Context, err error, opts ...trace.EventOption) {
if err == nil {
return
}
failSpan(trace.SpanFromContext(ctx), err, opts...)
}
// TraceID returns the hex trace ID of the span in ctx, or "" if there is none.
// Useful for returning a correlation ID to clients.
func TraceID(ctx context.Context) string {
sc := trace.SpanContextFromContext(ctx)
if !sc.HasTraceID() {
return ""
}
return sc.TraceID().String()
}
func failSpan(span trace.Span, err error, opts ...trace.EventOption) {
span.RecordError(err, opts...)
span.SetStatus(codes.Error, err.Error())
} }
+189
View File
@@ -2,13 +2,18 @@ package obsx
import ( import (
"context" "context"
"errors"
"slices"
"testing" "testing"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest" "go.opentelemetry.io/otel/sdk/trace/tracetest"
semconv "go.opentelemetry.io/otel/semconv/v1.26.0" semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
"go.opentelemetry.io/otel/trace"
) )
func setupTestTracer(t *testing.T) *tracetest.InMemoryExporter { func setupTestTracer(t *testing.T) *tracetest.InMemoryExporter {
@@ -39,6 +44,9 @@ func TestSetupTracer_SetsGlobalProvider(t *testing.T) {
if _, ok := tp.(*sdktrace.TracerProvider); !ok { if _, ok := tp.(*sdktrace.TracerProvider); !ok {
t.Errorf("expected *sdktrace.TracerProvider, got %T", tp) t.Errorf("expected *sdktrace.TracerProvider, got %T", tp)
} }
if f := otel.GetTextMapPropagator().Fields(); len(f) == 0 {
t.Error("expected a global propagator to be installed")
}
} }
func TestSetupTracer_DefaultSampler(t *testing.T) { func TestSetupTracer_DefaultSampler(t *testing.T) {
@@ -122,3 +130,184 @@ func TestStartSpan_CreatesSpan(t *testing.T) {
t.Errorf("expected span name 'my-operation', got %q", spans[0].Name) t.Errorf("expected span name 'my-operation', got %q", spans[0].Name)
} }
} }
func TestNewExporter_Selection(t *testing.T) {
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
t.Setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "")
ctx := context.Background()
exp, err := newExporter(ctx, TracerConfig{Protocol: ProtocolGRPC})
if err != nil || exp != nil {
t.Errorf("no endpoint: exporter = %v, err = %v; want nil, nil", exp, err)
}
for _, cfg := range []TracerConfig{
{Protocol: ProtocolGRPC, Endpoint: "localhost:4317"},
{Protocol: ProtocolGRPC, Endpoint: "https://collector:4317", Headers: map[string]string{"x-token": "t"}},
{Protocol: ProtocolHTTP, Endpoint: "localhost:4318"},
{Protocol: "http/protobuf", Endpoint: "http://localhost:4318/v1/traces"},
} {
exp, err := newExporter(ctx, cfg)
if err != nil || exp == nil {
t.Errorf("%+v: exporter = %v, err = %v", cfg, exp, err)
continue
}
_ = exp.Shutdown(ctx)
}
if _, err := newExporter(ctx, TracerConfig{Protocol: "thrift", Endpoint: "x:1"}); err == nil {
t.Error("expected error for unsupported protocol")
}
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317")
exp, err = newExporter(ctx, TracerConfig{Protocol: ProtocolGRPC})
if err != nil || exp == nil {
t.Errorf("env endpoint: exporter = %v, err = %v", exp, err)
} else {
_ = exp.Shutdown(ctx)
}
}
func TestNewTracerProvider_NoExporterStillTraces(t *testing.T) {
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
t.Setenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "")
tp, shutdown, err := newTracerProvider(context.Background(), TracerConfig{ServiceName: "local"})
if err != nil {
t.Fatal(err)
}
defer shutdown(context.Background())
ctx, span := tp.Tracer("t").Start(context.Background(), "op")
defer span.End()
if TraceID(ctx) == "" {
t.Error("spans must have trace IDs even without an exporter (log correlation)")
}
}
func TestNewTracerProvider_Disabled(t *testing.T) {
tp, shutdown, err := newTracerProvider(context.Background(), TracerConfig{Disabled: true, Endpoint: "localhost:4317"})
if err != nil {
t.Fatal(err)
}
if err := shutdown(context.Background()); err != nil {
t.Error(err)
}
ctx, span := tp.Tracer("t").Start(context.Background(), "op")
span.End()
if TraceID(ctx) != "" {
t.Error("disabled tracing must not create spans")
}
}
func TestNewTracerProvider_ParentBasedSampling(t *testing.T) {
exp := tracetest.NewInMemoryExporter()
tp, shutdown, err := newTracerProvider(context.Background(), TracerConfig{Sampler: 0.000001, Exporter: exp})
if err != nil {
t.Fatal(err)
}
defer shutdown(context.Background())
// A sampled parent from an upstream service must be honored.
parent := trace.NewSpanContext(trace.SpanContextConfig{
TraceID: trace.TraceID{1},
SpanID: trace.SpanID{1},
TraceFlags: trace.FlagsSampled,
Remote: true,
})
_, span := tp.Tracer("t").Start(trace.ContextWithRemoteSpanContext(context.Background(), parent), "child")
if !span.SpanContext().IsSampled() {
t.Error("child of a sampled remote parent must be sampled")
}
span.End()
}
func TestNewResource_Attributes(t *testing.T) {
res, err := newResource(context.Background(), TracerConfig{
ServiceName: "svc",
ServiceVersion: "v1",
Environment: "prod",
Attributes: []attribute.KeyValue{attribute.String("team", "payments")},
})
if err != nil {
t.Fatal(err)
}
got := map[string]string{}
for _, kv := range res.Attributes() {
got[string(kv.Key)] = kv.Value.Emit()
}
for k, v := range map[string]string{
"service.name": "svc",
"service.version": "v1",
"deployment.environment.name": "prod",
"team": "payments",
} {
if got[k] != v {
t.Errorf("resource %s = %q, want %q", k, got[k], v)
}
}
if got["service.instance.id"] == "" {
t.Error("service.instance.id not set")
}
}
func TestTrace_RecordsError(t *testing.T) {
prev := otel.GetTracerProvider()
t.Cleanup(func() { otel.SetTracerProvider(prev) })
exp := setupTestTracer(t)
want := errors.New("failed")
var inner context.Context
err := Trace(context.Background(), "work", func(ctx context.Context) error {
inner = ctx
return want
})
if !errors.Is(err, want) {
t.Fatalf("Trace returned %v", err)
}
if TraceID(inner) == "" {
t.Error("fn context carries no span")
}
spans := exp.GetSpans()
if len(spans) != 1 || spans[0].Status.Code != codes.Error || len(spans[0].Events) != 1 {
t.Errorf("unexpected spans: %+v", spans)
}
}
func TestRecordError(t *testing.T) {
prev := otel.GetTracerProvider()
t.Cleanup(func() { otel.SetTracerProvider(prev) })
exp := setupTestTracer(t)
ctx, span := StartSpan(context.Background(), "op")
RecordError(ctx, nil)
RecordError(ctx, errors.New("bad"))
span.End()
s := exp.GetSpans()[0]
if s.Status.Code != codes.Error || len(s.Events) != 1 {
t.Errorf("unexpected span: status=%v events=%d", s.Status.Code, len(s.Events))
}
if TraceID(context.Background()) != "" {
t.Error("TraceID without span must be empty")
}
}
func TestSetupTracer_SetsPropagator(t *testing.T) {
prevTP, prevProp := otel.GetTracerProvider(), otel.GetTextMapPropagator()
t.Cleanup(func() {
otel.SetTracerProvider(prevTP)
otel.SetTextMapPropagator(prevProp)
})
shutdown, err := SetupTracer(context.Background(), TracerConfig{Exporter: tracetest.NewInMemoryExporter()})
if err != nil {
t.Fatal(err)
}
defer shutdown(context.Background())
fields := otel.GetTextMapPropagator().Fields()
if !slices.Contains(fields, "traceparent") || !slices.Contains(fields, "baggage") {
t.Errorf("propagator fields = %v, want traceparent and baggage", fields)
}
}