Skip to content

Options reference

The authoritative per-symbol API lives on pkg.go.dev; this is the at-a-glance map for Phase 1.

Constructors

func New(opts ...Option) (*Metrics, error)          // registry + collectors
func Register(mux *http.ServeMux, opts ...Option) error // New + MountOn

(*Metrics) methods:

Method Purpose
Registry() *prometheus.Registry the underlying registry (register more collectors)
BuildInfo() BuildInfo resolved version/revision/Go version, for label stamping
Handler() http.Handler the Prometheus/OpenMetrics exposition handler (unwrapped)
MountOn(mux *http.ServeMux) mount /metrics (+pprof) with the configured middleware

Options

Option Default Effect
WithRegistry(*prometheus.Registry) fresh private registry supply your own (register app collectors)
WithCollectors(...prometheus.Collector) register extra collectors
WithoutRuntimeCollectors() runtime on drop the Go + process collectors (keeps build_info)
WithBuildInfo(BuildInfo) auto-detected override version/revision/Go-version/name
WithMetricsPath(string) /metrics endpoint path
WithMiddleware(...func(http.Handler) http.Handler) none (warns) guard chain (auth); first is outermost
WithPprof() off also mount net/http/pprof behind the guard
WithPprofPath(string) /debug/pprof/ pprof prefix (must end in /)
WithLogger(*slog.Logger) slog.Default() logger for the unguarded-mount warning

Default collectors

New() registers, on a private *prometheus.Registry:

  • collectors.NewGoCollector()go_*
  • collectors.NewProcessCollector(...)process_*
  • a build_info gauge (constant 1) labelled version, revision, goversion (and name when BuildInfo.Name is set)

BuildInfo

type BuildInfo struct {
    Version   string // falls back to the main module version
    Revision  string // falls back to the vcs.revision build setting
    GoVersion string // falls back to runtime.Version()
    Name      string // optional tool-name label; omitted when empty
}

HTTP request instrumentation

func (m *Metrics) HTTPMiddleware(opts ...HTTPOption) (func(http.Handler) http.Handler, error)

Records http_requests_total, http_request_duration_seconds, http_requests_in_flight (labels method/route/status; route is the template from http.Request.Pattern). See Instrument HTTP requests.

HTTPOption Effect
WithHTTPNamespace(string) metric-name prefix
WithDurationBuckets(...float64) histogram buckets (default DefBuckets)
WithStatusClass() status label as class (2xx)
WithRouteLabelFunc(func(*http.Request) string) custom route-template source
WithUnmatchedRouteLabel(string) bucket for unmatched routes (default <other>)
WithHTTPConstLabels(prometheus.Labels) constant labels

Exemplars

type ExemplarSource func(context.Context) (traceID string, ok bool)
func WithExemplarSource(ExemplarSource) Option  // core Option
func (m *Metrics) ExemplarSource() ExemplarSource
func (m *Metrics) Observe(ctx, obs prometheus.Observer, v float64) // shared exemplar-aware observe

Enables trace_id exemplars on duration histograms. See Link metrics to traces.

Subpackages

Each pulls its heavy dep only when imported.

metrics/server (…/transport-metrics/server) — standalone server (pulls go/transport):

func New(ctx, transporthttp.ServerSettings, *metrics.Metrics, ...transporthttp.ServerOption) (*http.Server, error)

metrics/grpc (…/transport-metrics/grpc, import aliased) — gRPC RED interceptors (pulls google.golang.org/grpc):

func NewServerMetrics(*metrics.Metrics, ...Option) (*ServerMetrics, error)
func (*ServerMetrics) UnaryInterceptor() grpc.UnaryServerInterceptor
func (*ServerMetrics) StreamInterceptor() grpc.StreamServerInterceptor
// grpc_server_handled_total{grpc_method,grpc_code}, grpc_server_handling_seconds, grpc_server_in_flight

metrics/otel (…/transport-metrics/otel) — OTel exemplar source (pulls go.opentelemetry.io/otel/trace):

func ExemplarSource() metrics.ExemplarSource

RED/USE domain helpers

All take the shared HelperOption set (WithNamespace, WithBuckets, WithConstLabels) and register on m's registry. See Instrument business logic and Instrument resources.

Constructor Records Const label
NewOperations(opts...) operations_total / operation_errors_total / operation_duration_seconds / operations_in_flight (label operation)
NewDB(name, opts...) query RED (db_queries_total, db_query_errors_total, db_query_duration_seconds, db_queries_in_flight; label query) db
NewCache(name, opts...) cache_hits_total / _misses_total / _evictions_total / cache_size / cache_capacity cache
NewCircuitBreaker(name, opts...) circuit_breaker_state (0/½) + _trips_total / _short_circuits_total / _successes_total / _failures_total name
NewQueue(name, opts...) queue_depth / queue_enqueued_total / _dequeued_total / queue_wait_seconds / queue_processing_seconds queue

Business-logic wrapper:

func (o *Operations) Observe(ctx, name string, fn func() error) error
func ObserveResult[T any](o *Operations, ctx, name string, fn func() (T, error)) (T, error)

Database pool USE (opt-in):

func (d *DB) RegisterPool(fn func() PoolStats) error // scrape-time db_pool_* gauges
type PoolStats struct { MaxOpen, Open, InUse, Idle int; WaitCount int64; WaitSeconds float64 }