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:
1 parent
8398e81bc7
commit
be4330a9ee
7 files changed
+1087
-1
No files matched your search
+276
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user