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>
161 lines
5.2 KiB
Go
161 lines
5.2 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.
|
|
func (m *Metrics) GaugeFunc(name, help string, fn func() float64) {
|
|
register[prometheus.Collector](m.registry, 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.
|
|
func (m *Metrics) CounterFunc(name, help string, fn func() float64) {
|
|
register[prometheus.Collector](m.registry, 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.
|
|
func (m *Metrics) RegisterDBStats(db *sql.DB, name string) {
|
|
register(m.registry, 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)
|
|
}
|