Help us shape the future of Go! Take the 2026 Go Developer Survey

prometheus

package
v0.10.154 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 12 Imported by: 1

Documentation

Overview

Package prometheus provides a metrics.Sink backed by the Prometheus client library.

A Sink is itself a prometheus.Collector: it registers with a prometheus.Registerer on construction and is scraped over HTTP by promhttp. Metric families are created lazily on first emission, so the set of exported series grows with the tag combinations the application actually uses.

Mapping from the metrics package:

  • SetGauge -> prometheus.Gauge
  • IncrCounter-> prometheus.Counter
  • AddSample -> prometheus.Summary with 0.5/0.9/0.99 objectives

Metric names are sanitized by replacing the characters " ", ".", "=", "-" and "/" with "_". Tag names are passed through unchanged; the Prometheus client escapes names that are not legacy-valid at exposition time. A series the client library rejects outright (an empty name, a label name with the reserved "__" prefix, invalid UTF-8) is dropped and logged, because one erroring descriptor would fail every scrape until the series expires.

Expiration

Gauges and summaries created at runtime are removed after Opts.Expiration without an update, which keeps ephemeral tag combinations from accumulating. Counters are kept by default, because deleting a counter resets the series and breaks rate() over the gap; set Opts.CounterExpiration when the label cardinality is unbounded and a reset is the lesser problem. Series pre-declared through Opts.GaugeDefinitions, Opts.SummaryDefinitions and Opts.CounterDefinitions are initialized at zero and never expire.

Usage

sink, err := prometheus.NewSinkFrom(prometheus.Opts{
	Name:       "billing",
	Expiration: time.Minute,
	Registerer: prom.DefaultRegisterer,
	Help:       cfg.Help(billing.Metrics),
})
if err != nil {
	return err
}
if _, err := metrics.NewGlobal(cfg, sink); err != nil {
	return err
}
http.Handle("/metrics", promhttp.Handler())

Use NewPushSinkFrom instead to push to a Prometheus Pushgateway on an interval, and PushSink.Shutdown to stop it.

Index

Constants

View Source
const ObservationMaxAge = 10 * time.Minute

ObservationMaxAge is the duration for which an observation stays relevant for the quantiles of a summary. It does not apply to _sum and _count, and is independent of Opts.Expiration.

Variables

View Source
var DefaultPrometheusOpts = Opts{
	Expiration: defaultExpiration,
	Name:       defaultSinkName,
}

DefaultPrometheusOpts is the default set of options used when creating a Sink with NewSink.

It is a package-level variable so that it can be adjusted before the sink is created; changing it afterwards has no effect.

Functions

This section is empty.

Types

type CounterDefinition

type CounterDefinition struct {
	Name      string
	ConstTags []metrics.Tag
	Help      string
}

CounterDefinition can be provided to Opts to declare a constant counter that is not deleted on expiry.

type GaugeDefinition

type GaugeDefinition struct {
	Name      string
	ConstTags []metrics.Tag
	Help      string
}

GaugeDefinition can be provided to Opts to declare a constant gauge that is not deleted on expiry.

type Opts

type Opts struct {
	// Expiration is the duration a gauge or summary is valid for, after which
	// it will be untracked. If the value is not positive, they are never
	// expired. Counters are controlled by CounterExpiration instead.
	Expiration time.Duration

	// CounterExpiration is the duration after which a counter created at
	// runtime is removed, when it has not been updated. The zero value, which
	// is the default, keeps every counter for the lifetime of the process, as
	// does a negative one.
	//
	// Deleting a counter resets the series, which makes rate() over the gap
	// wrong, so only set this when the label cardinality is unbounded and a
	// reset is the lesser problem.
	CounterExpiration time.Duration

	// Registerer the Sink registers itself with.
	// Defaults to prometheus.DefaultRegisterer.
	Registerer prometheus.Registerer

	// GaugeDefinitions pre-declares gauges by Name, Help and ConstTags.
	// Metrics declared in this way will be initialized at zero and will not be
	// deleted or altered when their expiry is reached.
	//
	// Ex: Opts{
	//     Expiration: 10 * time.Second,
	//     GaugeDefinitions: []GaugeDefinition{
	//         {
	//           Name: "application_component_measurement",
	//           Help: "application_component_measurement provides an example of how to declare static metrics",
	//           ConstTags: []metrics.Tag{ { Name: "my_label", Value: "does_not_change" } },
	//         },
	//     },
	// }
	GaugeDefinitions []GaugeDefinition
	// SummaryDefinitions pre-declares summaries, see GaugeDefinitions.
	SummaryDefinitions []SummaryDefinition
	// CounterDefinitions pre-declares counters, see GaugeDefinitions.
	CounterDefinitions []CounterDefinition

	// Name of the sink, used as the descriptor exposed by Describe.
	// Two sinks registered with the same Registerer must have different names.
	Name string

	// Help of the metrics, keyed by the final metric name.
	// Use metrics.Config.Help to build it from the metric descriptions, so the
	// exported HELP text matches the name the configuration produces.
	// The map is retained and written to by the pre-declared definitions; it
	// must not be modified once the sink is constructed.
	Help map[string]string
}

Opts is used to configure the Prometheus Sink.

type PushSink

type PushSink struct {
	*Sink
	// contains filtered or unexported fields
}

PushSink wraps a normal prometheus sink and provides an address and facilities to export it to an address on an interval.

Use it for processes that Prometheus cannot scrape, such as batch jobs, by pushing to a Pushgateway.

func NewPushSink

func NewPushSink(address string, pushInterval time.Duration, name string) (*PushSink, error)

NewPushSink creates a PushSink by taking an address, interval, and destination name, and starts the background push loop.

The wrapped Sink is not registered with any prometheus.Registerer and uses a 60s expiration. Use NewPushSinkFrom to configure it. Call Shutdown to stop pushing. pushInterval must be greater than zero.

func NewPushSinkFrom added in v0.10.151

func NewPushSinkFrom(address string, pushInterval time.Duration, name string, opts Opts) (*PushSink, error)

NewPushSinkFrom creates a PushSink with the given options and starts the background push loop. name is the job name reported to the Pushgateway.

The wrapped Sink is registered only when opts.Registerer is set, since a pushed sink is usually not scraped as well. pushInterval must be greater than zero.

func (*PushSink) Shutdown

func (s *PushSink) Shutdown()

Shutdown tears down the PushSink, and blocks while flushing metrics to the backend. It is idempotent, and a concurrent call returns once the teardown is complete.

It waits for the background loop to finish before the final push: a push already in flight must not run concurrently with it, since the two would share one push.Pusher.

type Sink

type Sink struct {
	// contains filtered or unexported fields
}

Sink provides a metrics.Sink that can be used with a prometheus server.

It implements prometheus.Collector: it is registered on construction and scraped through a prometheus registry. Series are created on first use and, unless pre-declared, expired after Opts.Expiration without an update. It is safe for concurrent emission and concurrent scrapes.

func NewSink

func NewSink() (*Sink, error)

NewSink creates a new Sink using DefaultPrometheusOpts.

func NewSinkFrom

func NewSinkFrom(opts Opts) (*Sink, error)

NewSinkFrom creates a new Sink using the passed options and registers it with opts.Registerer, or with prometheus.DefaultRegisterer when unset.

It returns an error, and no sink, when a collector with the same name is already registered with that registerer. The cause is preserved, so errors.As with prometheus.AlreadyRegisteredError still works.

func (*Sink) AddSample

func (p *Sink) AddSample(parts string, val float64, labels []metrics.Tag)

AddSample records an observation in a summary, exported as the configured quantiles plus _sum and _count. The summary is created on first use and expires after Opts.Expiration. An emission the client library would reject is dropped and reported.

func (*Sink) Collect

func (p *Sink) Collect(c chan<- prometheus.Metric)

Collect meets the collection interface and allows us to enforce our expiration logic to clean up ephemeral metrics if their value haven't been set for a duration exceeding our allowed expiration time.

func (*Sink) Describe

func (p *Sink) Describe(c chan<- *prometheus.Desc)

Describe sends a Collector.Describe value from the descriptor created around Sink.Name Note that we cannot describe all the metrics (gauges, counters, summaries) in the sink as metrics can be added at any point during the lifecycle of the sink, which does not respect the idempotency aspect of the Collector.Describe() interface

func (*Sink) IncrCounter

func (p *Sink) IncrCounter(parts string, val float64, labels []metrics.Tag)

IncrCounter accumulates values. The counter is created on first use and, unless Opts.CounterExpiration is set, is retained for the lifetime of the process. An emission the client library would reject is dropped and reported.

func (*Sink) SetGauge

func (p *Sink) SetGauge(parts string, val float64, labels []metrics.Tag)

SetGauge retains the last value it is set to. The gauge is created on first use and expires after Opts.Expiration. An emission the client library would reject is dropped and reported.

type SummaryDefinition

type SummaryDefinition struct {
	Name      string
	ConstTags []metrics.Tag
	Help      string
}

SummaryDefinition can be provided to Opts to declare a constant summary that is not deleted on expiry.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL