Files
obsx/observer.go
T
M.ShakhmatovandClaude Fable 5.2 c92fd9826b
CI / test (push) Failing after 43s
Harden instrumentation, health checks and the admin server
- 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

297 lines
9.1 KiB
Go

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
}