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>
This commit is contained in:
M.ShakhmatovandClaude Opus 5.5 committed 2026-10-30 00:18:43 +03:00
1 parent e8c211e93f
commit f7c8186040
6 files changed
+1092

No files matched your search

+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 (unless Admin.DisablePprof)
//
// Expose it on an internal port 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.DisablePprof {
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)
}
})
}
+172
View File
@@ -1 +1,173 @@
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
// 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 /debug/pprof/.
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
DisablePprof 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_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_DISABLE_PPROF Admin.DisablePprof
// 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")
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.DisablePprof, "OBSX_ADMIN_DISABLE_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)
}
+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", 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)
}
}
+276
View File
@@ -0,0 +1,276 @@
package obsx
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"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. 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
func (o *Observer) HTTPMiddleware(next http.Handler) http.Handler {
return NewHTTPMiddleware(HTTPServerConfig{
Metrics: o.metrics,
Logger: o.accessLogger(),
TracerProvider: o.tp,
})(next)
}
// HTTPTransport wraps base (http.DefaultTransport when nil) with client
// tracing, context propagation and metrics.
func (o *Observer) HTTPTransport(base http.RoundTripper) http.RoundTripper {
return NewHTTPTransport(base, HTTPClientConfig{
Metrics: o.metrics,
TracerProvider: o.tp,
})
}
// 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.
func (o *Observer) GRPCInterceptors() *GRPCInterceptors {
return NewGRPCInterceptors(GRPCConfig{
Metrics: o.metrics,
Logger: o.accessLogger(),
TracerProvider: o.tp,
Skip: func(fullMethod string) bool {
return fullMethod == "/grpc.health.v1.Health/Check" || fullMethod == "/grpc.health.v1.Health/Watch"
},
})
}
// 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
}
+332
View File
@@ -0,0 +1,332 @@
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"}})
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_AdminDisablePprof(t *testing.T) {
o, _, _ := newTestObserver(t, Config{Admin: AdminConfig{DisablePprof: true}})
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_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 {
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")
}
}