Options reference¶
Every constructor and option in the module, with its default. The authoritative per-symbol API lives on pkg.go.dev; this is the at-a-glance map.
For the series these produce see the metrics reference; for what each one does when it is wrong see failure modes.
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. Returns nothing; panics if the mux rejects the pattern |
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 |
WithExemplarSource(ExemplarSource) |
none | trace-id source for duration-histogram exemplars |
Options are applied in the order given, and later wins for the single-valued ones
(WithMetricsPath, WithPprofPath, WithRegistry, WithBuildInfo, WithLogger,
WithExemplarSource). WithCollectors and WithMiddleware accumulate across
calls rather than replacing, so passing WithMiddleware(a) and then
WithMiddleware(b) gives you the chain a → b, with a outermost.
What each core option does when it is wrong¶
| Option | Wrong value | What happens |
|---|---|---|
WithRegistry |
a registry already carrying a Go collector | New returns register go collector: duplicate metrics collector registration attempted. Add WithoutRuntimeCollectors(). |
WithMetricsPath |
no leading slash ("metrics") |
panic at mount: parsing "GET metrics": at offset 4: host/path missing /. Not validated. |
WithPprofPath |
no trailing slash ("/debug/pprof") |
No error. Sub-handlers land at /debug/pprofcmdline and friends; go tool pprof fails. Not validated. |
WithMiddleware |
omitted | A WARN on every mount. Not an error — see failure modes. |
WithBuildInfo |
empty fields | Each empty field falls back to the build's embedded metadata, then to the literal unknown. |
WithExemplarSource |
unset | No exemplars are recorded. No warning. |
Default collectors¶
New() registers, on a private *prometheus.Registry:
collectors.NewGoCollector()—go_*collectors.NewProcessCollector(...)—process_*- a
build_infogauge (constant1) labelledversion,revision,goversion(andnamewhenBuildInfo.Nameis 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¶
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, ...server.Option) (*http.Server, error)
const DefaultHost = "127.0.0.1" // loopback: the default bind host
func WithHost(host string) Option // override the bind host ("" = all interfaces)
func WithBindAddress(host string) Option // alias for WithHost
func WithServerOptions(...transporthttp.ServerOption) Option // port, TLS, timeouts
The server binds 127.0.0.1 (loopback) by default — a metrics/pprof port must
not be openly reachable. Pass WithHost/WithBindAddress (with "" for all
interfaces, or a specific address) to opt out. See
the standalone-server how-to
for the migration note.
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):
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=closed, 1=open, 2=half-open) + _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):