Files
obsx/metrics.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

164 lines
5.4 KiB
Go

package obsx
import (
"context"
"database/sql"
"errors"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/otel/trace"
)
// MetricsConfig configures the metrics factory.
type MetricsConfig struct {
Namespace string
Subsystem string
}
// 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 {
cfg MetricsConfig
registry *prometheus.Registry
}
// NewMetrics creates a new Metrics factory backed by an isolated registry
// pre-loaded with process and Go runtime collectors.
func NewMetrics(cfg MetricsConfig) *Metrics {
reg := prometheus.NewRegistry()
reg.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
reg.MustRegister(collectors.NewGoCollector())
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.
func (m *Metrics) Counter(name, help string, labels ...string) *prometheus.CounterVec {
return register(m.registry, prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: m.cfg.Namespace,
Subsystem: m.cfg.Subsystem,
Name: name,
Help: help,
}, labels))
}
// 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 {
if buckets == nil {
buckets = prometheus.DefBuckets
}
return register(m.registry, prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: m.cfg.Namespace,
Subsystem: m.cfg.Subsystem,
Name: name,
Help: help,
Buckets: buckets,
}, labels))
}
// Gauge creates and registers a new GaugeVec.
func (m *Metrics) Gauge(name, help string, labels ...string) *prometheus.GaugeVec {
return register(m.registry, prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: m.cfg.Namespace,
Subsystem: m.cfg.Subsystem,
Name: name,
Help: help,
}, labels))
}
// 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.
// OpenMetrics format is negotiated when requested, which exposes trace
// exemplars attached by the built-in instrumentation.
func (m *Metrics) Handler() http.Handler {
return promhttp.HandlerFor(m.registry, promhttp.HandlerOpts{
EnableOpenMetrics: true,
})
}
// Registry returns the underlying Prometheus registry.
func (m *Metrics) Registry() *prometheus.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)
}