prometheus

package
v0.0.0-...-83adff0 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2020 License: GPL-3.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefMaxAge is the default duration for which observations stay
	// relevant.
	DefMaxAge time.Duration = 10 * time.Minute
	// DefAgeBuckets is the default number of buckets used to calculate the
	// age of observations.
	DefAgeBuckets = 5
	// DefBufCap is the standard buffer size for collecting Summary observations.
	DefBufCap = 500
)

Default values for SummaryOpts.

Variables

View Source
var (
	DefaultRegisterer Registerer = defaultRegistry
	DefaultGatherer   Gatherer   = defaultRegistry
)

DefaultRegisterer and DefaultGatherer are the implementations of the Registerer and Gatherer interface a number of convenience functions in this package act on. Initially, both variables point to the same Registry, which has a process collector (see NewProcessCollector) and a Go collector (see NewGoCollector) already registered. This approach to keep default instances as global state mirrors the approach of other packages in the Go standard library. Note that there are caveats. Change the variables with caution and only if you understand the consequences. Users who want to avoid global state altogether should not use the convenience function and act on custom instances instead.

View Source
var (
	DefObjectives = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}
)

DefObjectives are the default Summary quantile values.

Deprecated: DefObjectives will not be used as the default objectives in v0.10 of the library. The default Summary will have no quantiles then.

Functions

func BuildFQName

func BuildFQName(namespace, subsystem, name string) string

BuildFQName joins the given three name components by "_". Empty name components are ignored. If the name parameter itself is empty, an empty string is returned, no matter what. Metric implementations included in this library use this function internally to generate the fully-qualified metric name from the name component in their Opts. Users of the library will only need this function if they implement their own Metric or instantiate a Desc (with NewDesc) directly.

func MustRegister

func MustRegister(cs ...Collector)

MustRegister registers the provided Collectors with the DefaultRegisterer and panics if any error occurs.

MustRegister is a shortcut for DefaultRegisterer.MustRegister(cs...). See there for more details.

func Register

func Register(c Collector) error

Register registers the provided Collector with the DefaultRegisterer.

Register is a shortcut for DefaultRegisterer.Register(c). See there for more details.

func Unregister

func Unregister(c Collector) bool

Unregister removes the registration of the provided Collector from the DefaultRegisterer.

Unregister is a shortcut for DefaultRegisterer.Unregister(c). See there for more details.

Types

type AlreadyRegisteredError

type AlreadyRegisteredError struct {
	ExistingCollector, NewCollector Collector
}

AlreadyRegisteredError is returned by the Register method if the Collector to be registered has already been registered before, or a different Collector that collects the same metrics has been registered before. Registration fails in that case, but you can detect from the kind of error what has happened. The error contains fields for the existing Collector and the (rejected) new Collector that equals the existing one. This can be used to find out if an equal Collector has been registered before and switch over to using the old one, as demonstrated in the example.

func (AlreadyRegisteredError) Error

func (err AlreadyRegisteredError) Error() string

type Collector

type Collector interface {
	// Describe sends the super-set of all possible descriptors of metrics
	// collected by this Collector to the provided channel and returns once
	// the last descriptor has been sent. The sent descriptors fulfill the
	// consistency and uniqueness requirements described in the Desc
	// documentation. (It is valid if one and the same Collector sends
	// duplicate descriptors. Those duplicates are simply ignored. However,
	// two different Collectors must not send duplicate descriptors.) This
	// method idempotently sends the same descriptors throughout the
	// lifetime of the Collector. If a Collector encounters an error while
	// executing this method, it must send an invalid descriptor (created
	// with NewInvalidDesc) to signal the error to the registry.
	Describe(chan<- *Desc)
	// Collect is called by the Prometheus registry when collecting
	// metrics. The implementation sends each collected metric via the
	// provided channel and returns once the last metric has been sent. The
	// descriptor of each sent metric is one of those returned by
	// Describe. Returned metrics that share the same descriptor must differ
	// in their variable label values. This method may be called
	// concurrently and must therefore be implemented in a concurrency safe
	// way. Blocking occurs at the expense of total performance of rendering
	// all registered metrics. Ideally, Collector implementations support
	// concurrent readers.
	Collect(chan<- Metric)
}

Collector is the interface implemented by anything that can be used by Prometheus to collect metrics. A Collector has to be registered for collection. See Registerer.Register.

The stock metrics provided by this package (Gauge, Counter, Summary, Histogram, Untyped) are also Collectors (which only ever collect one metric, namely itself). An implementer of Collector may, however, collect multiple metrics in a coordinated fashion and/or create metrics on the fly. Examples for collectors already implemented in this library are the metric vectors (i.e. collection of multiple instances of the same Metric but with different label values) like GaugeVec or SummaryVec, and the ExpvarCollector.

func NewGoCollector

func NewGoCollector() Collector

NewGoCollector returns a collector which exports metrics about the current go process.

func NewProcessCollector

func NewProcessCollector(pid int, namespace string) Collector

NewProcessCollector returns a collector which exports the current state of process metrics including cpu, memory and file descriptor usage as well as the process start time for the given process id under the given namespace.

func NewProcessCollectorPIDFn

func NewProcessCollectorPIDFn(
	pidFn func() (int, error),
	namespace string,
) Collector

NewProcessCollectorPIDFn returns a collector which exports the current state of process metrics including cpu, memory and file descriptor usage as well as the process start time under the given namespace. The given pidFn is called on each collect and is used to determine the process to export metrics for.

type Counter

type Counter interface {
	Metric
	Collector

	// Inc increments the counter by 1. Use Add to increment it by arbitrary
	// non-negative values.
	Inc()
	// Add adds the given value to the counter. It panics if the value is <
	// 0.
	Add(float64)
	// Value return value
	Value() float64
	// Lables return Lables
	Lables() []*dto.LabelPair
}

Counter is a Metric that represents a single numerical value that only ever goes up. That implies that it cannot be used to count items whose number can also go down, e.g. the number of currently running goroutines. Those "counters" are represented by Gauges.

A Counter is typically used to count requests served, tasks completed, errors occurred, etc.

To create Counter instances, use NewCounter.

func NewCounter

func NewCounter(opts CounterOpts) Counter

NewCounter creates a new Counter based on the provided CounterOpts.

type CounterFunc

type CounterFunc interface {
	Metric
	Collector
}

CounterFunc is a Counter whose value is determined at collect time by calling a provided function.

To create CounterFunc instances, use NewCounterFunc.

func NewCounterFunc

func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc

NewCounterFunc creates a new CounterFunc based on the provided CounterOpts. The value reported is determined by calling the given function from within the Write method. Take into account that metric collection may happen concurrently. If that results in concurrent calls to Write, like in the case where a CounterFunc is directly registered with Prometheus, the provided function must be concurrency-safe. The function should also honor the contract for a Counter (values only go up, not down), but compliance will not be checked.

type CounterOpts

type CounterOpts Opts

CounterOpts is an alias for Opts. See there for doc comments.

type CounterVec

type CounterVec struct {
	*MetricVec
}

CounterVec is a Collector that bundles a set of Counters that all share the same Desc, but have different values for their variable labels. This is used if you want to count the same thing partitioned by various dimensions (e.g. number of HTTP requests, partitioned by response code and method). Create instances with NewCounterVec.

CounterVec embeds MetricVec. See there for a full list of methods with detailed documentation.

func NewCounterVec

func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec

NewCounterVec creates a new CounterVec based on the provided CounterOpts and partitioned by the given label names. At least one label name must be provided.

func (*CounterVec) GetMetricWith

func (m *CounterVec) GetMetricWith(labels Labels) (Counter, error)

GetMetricWith replaces the method of the same name in MetricVec. The difference is that this method returns a Counter and not a Metric so that no type conversion is required.

func (*CounterVec) GetMetricWithLabelValues

func (m *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error)

GetMetricWithLabelValues replaces the method of the same name in MetricVec. The difference is that this method returns a Counter and not a Metric so that no type conversion is required.

func (*CounterVec) With

func (m *CounterVec) With(labels Labels) Counter

With works as GetMetricWith, but panics where GetMetricWithLabels would have returned an error. By not returning an error, With allows shortcuts like

myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)

func (*CounterVec) WithLabelValues

func (m *CounterVec) WithLabelValues(lvs ...string) Counter

WithLabelValues works as GetMetricWithLabelValues, but panics where GetMetricWithLabelValues would have returned an error. By not returning an error, WithLabelValues allows shortcuts like

myVec.WithLabelValues("404", "GET").Add(42)

type Desc

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

Desc is the descriptor used by every Prometheus Metric. It is essentially the immutable meta-data of a Metric. The normal Metric implementations included in this package manage their Desc under the hood. Users only have to deal with Desc if they use advanced features like the ExpvarCollector or custom Collectors and Metrics.

Descriptors registered with the same registry have to fulfill certain consistency and uniqueness criteria if they share the same fully-qualified name: They must have the same help string and the same label names (aka label dimensions) in each, constLabels and variableLabels, but they must differ in the values of the constLabels.

Descriptors that share the same fully-qualified names and the same label values of their constLabels are considered equal.

Use NewDesc to create new Desc instances.

func NewDesc

func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc

NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc and will be reported on registration time. variableLabels and constLabels can be nil if no such labels should be set. fqName and help must not be empty.

variableLabels only contain the label names. Their label values are variable and therefore not part of the Desc. (They are managed within the Metric.)

For constLabels, the label values are constant. Therefore, they are fully specified in the Desc. See the Opts documentation for the implications of constant labels.

func NewInvalidDesc

func NewInvalidDesc(err error) *Desc

NewInvalidDesc returns an invalid descriptor, i.e. a descriptor with the provided error set. If a collector returning such a descriptor is registered, registration will fail with the provided error. NewInvalidDesc can be used by a Collector to signal inability to describe itself.

func (*Desc) String

func (d *Desc) String() string

type Gatherer

type Gatherer interface {
	// Gather calls the Collect method of the registered Collectors and then
	// gathers the collected metrics into a lexicographically sorted slice
	// of MetricFamily protobufs. Even if an error occurs, Gather attempts
	// to gather as many metrics as possible. Hence, if a non-nil error is
	// returned, the returned MetricFamily slice could be nil (in case of a
	// fatal error that prevented any meaningful metric collection) or
	// contain a number of MetricFamily protobufs, some of which might be
	// incomplete, and some might be missing altogether. The returned error
	// (which might be a MultiError) explains the details. In scenarios
	// where complete collection is critical, the returned MetricFamily
	// protobufs should be disregarded if the returned error is non-nil.
	Gather() ([]*dto.MetricFamily, error)
}

Gatherer is the interface for the part of a registry in charge of gathering the collected metrics into a number of MetricFamilies. The Gatherer interface comes with the same general implication as described for the Registerer interface.

type GathererFunc

type GathererFunc func() ([]*dto.MetricFamily, error)

GathererFunc turns a function into a Gatherer.

func (GathererFunc) Gather

func (gf GathererFunc) Gather() ([]*dto.MetricFamily, error)

Gather implements Gatherer.

type Gatherers

type Gatherers []Gatherer

Gatherers is a slice of Gatherer instances that implements the Gatherer interface itself. Its Gather method calls Gather on all Gatherers in the slice in order and returns the merged results. Errors returned from the Gather calles are all returned in a flattened MultiError. Duplicate and inconsistent Metrics are skipped (first occurrence in slice order wins) and reported in the returned error.

Gatherers can be used to merge the Gather results from multiple Registries. It also provides a way to directly inject existing MetricFamily protobufs into the gathering by creating a custom Gatherer with a Gather method that simply returns the existing MetricFamily protobufs. Note that no registration is involved (in contrast to Collector registration), so obviously registration-time checks cannot happen. Any inconsistencies between the gathered MetricFamilies are reported as errors by the Gather method, and inconsistent Metrics are dropped. Invalid parts of the MetricFamilies (e.g. syntactically invalid metric or label names) will go undetected.

func (Gatherers) Gather

func (gs Gatherers) Gather() ([]*dto.MetricFamily, error)

Gather implements Gatherer.

type LabelPairSorter

type LabelPairSorter []*dto.LabelPair

LabelPairSorter implements sort.Interface. It is used to sort a slice of dto.LabelPair pointers. This is useful for implementing the Write method of custom metrics.

func (LabelPairSorter) Len

func (s LabelPairSorter) Len() int

func (LabelPairSorter) Less

func (s LabelPairSorter) Less(i, j int) bool

func (LabelPairSorter) Swap

func (s LabelPairSorter) Swap(i, j int)

type Labels

type Labels map[string]string

Labels represents a collection of label name -> value mappings. This type is commonly used with the With(Labels) and GetMetricWith(Labels) methods of metric vector Collectors, e.g.:

myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)

The other use-case is the specification of constant label pairs in Opts or to create a Desc.

type Metric

type Metric interface {
	// Desc returns the descriptor for the Metric. This method idempotently
	// returns the same descriptor throughout the lifetime of the
	// Metric. The returned descriptor is immutable by contract. A Metric
	// unable to describe itself must return an invalid descriptor (created
	// with NewInvalidDesc).
	Desc() *Desc
	// Write encodes the Metric into a "Metric" Protocol Buffer data
	// transmission object.
	//
	// Metric implementations must observe concurrency safety as reads of
	// this metric may occur at any time, and any blocking occurs at the
	// expense of total performance of rendering all registered
	// metrics. Ideally, Metric implementations should support concurrent
	// readers.
	//
	// While populating dto.Metric, it is the responsibility of the
	// implementation to ensure validity of the Metric protobuf (like valid
	// UTF-8 strings or syntactically valid metric and label names). It is
	// recommended to sort labels lexicographically. (Implementers may find
	// LabelPairSorter useful for that.) Callers of Write should still make
	// sure of sorting if they depend on it.
	Write(*dto.Metric) error
}

A Metric models a single sample value with its meta data being exported to Prometheus. Implementations of Metric in this package are Gauge, Counter, Histogram, Summary, and Untyped.

func MustNewConstMetric

func MustNewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric

MustNewConstMetric is a version of NewConstMetric that panics where NewConstMetric would have returned an error.

func MustNewConstSummary

func MustNewConstSummary(
	desc *Desc,
	count uint64,
	sum float64,
	quantiles map[float64]float64,
	labelValues ...string,
) Metric

MustNewConstSummary is a version of NewConstSummary that panics where NewConstMetric would have returned an error.

func NewConstMetric

func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error)

NewConstMetric returns a metric with one fixed value that cannot be changed. Users of this package will not have much use for it in regular operations. However, when implementing custom Collectors, it is useful as a throw-away metric that is generated on the fly to send it to Prometheus in the Collect method. NewConstMetric returns an error if the length of labelValues is not consistent with the variable labels in Desc.

func NewConstSummary

func NewConstSummary(
	desc *Desc,
	count uint64,
	sum float64,
	quantiles map[float64]float64,
	labelValues ...string,
) (Metric, error)

NewConstSummary returns a metric representing a Prometheus summary with fixed values for the count, sum, and quantiles. As those parameters cannot be changed, the returned value does not implement the Summary interface (but only the Metric interface). Users of this package will not have much use for it in regular operations. However, when implementing custom Collectors, it is useful as a throw-away metric that is generated on the fly to send it to Prometheus in the Collect method.

quantiles maps ranks to quantile values. For example, a median latency of 0.23s and a 99th percentile latency of 0.56s would be expressed as:

map[float64]float64{0.5: 0.23, 0.99: 0.56}

NewConstSummary returns an error if the length of labelValues is not consistent with the variable labels in Desc.

func NewInvalidMetric

func NewInvalidMetric(desc *Desc, err error) Metric

NewInvalidMetric returns a metric whose Write method always returns the provided error. It is useful if a Collector finds itself unable to collect a metric and wishes to report an error to the registry.

type MetricVec

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

MetricVec is a Collector to bundle metrics of the same name that differ in their label values. MetricVec is usually not used directly but as a building block for implementations of vectors of a given metric type. GaugeVec, CounterVec, SummaryVec, and UntypedVec are examples already provided in this package.

func (*MetricVec) Collect

func (m *MetricVec) Collect(ch chan<- Metric)

Collect implements Collector.

func (*MetricVec) Delete

func (m *MetricVec) Delete(labels Labels) bool

Delete deletes the metric where the variable labels are the same as those passed in as labels. It returns true if a metric was deleted.

It is not an error if the number and names of the Labels are inconsistent with those of the VariableLabels in the Desc of the MetricVec. However, such inconsistent Labels can never match an actual Metric, so the method will always return false in that case.

This method is used for the same purpose as DeleteLabelValues(...string). See there for pros and cons of the two methods.

func (*MetricVec) DeleteLabelValues

func (m *MetricVec) DeleteLabelValues(lvs ...string) bool

DeleteLabelValues removes the metric where the variable labels are the same as those passed in as labels (same order as the VariableLabels in Desc). It returns true if a metric was deleted.

It is not an error if the number of label values is not the same as the number of VariableLabels in Desc. However, such inconsistent label count can never match an actual Metric, so the method will always return false in that case.

Note that for more than one label value, this method is prone to mistakes caused by an incorrect order of arguments. Consider Delete(Labels) as an alternative to avoid that type of mistake. For higher label numbers, the latter has a much more readable (albeit more verbose) syntax, but it comes with a performance overhead (for creating and processing the Labels map). See also the CounterVec example.

func (*MetricVec) Describe

func (m *MetricVec) Describe(ch chan<- *Desc)

Describe implements Collector. The length of the returned slice is always one.

func (*MetricVec) GetMetricWith

func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error)

GetMetricWith returns the Metric for the given Labels map (the label names must match those of the VariableLabels in Desc). If that label map is accessed for the first time, a new Metric is created. Implications of creating a Metric without using it and keeping the Metric for later use are the same as for GetMetricWithLabelValues.

An error is returned if the number and names of the Labels are inconsistent with those of the VariableLabels in Desc.

This method is used for the same purpose as GetMetricWithLabelValues(...string). See there for pros and cons of the two methods.

func (*MetricVec) GetMetricWithLabelValues

func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error)

GetMetricWithLabelValues returns the Metric for the given slice of label values (same order as the VariableLabels in Desc). If that combination of label values is accessed for the first time, a new Metric is created.

It is possible to call this method without using the returned Metric to only create the new Metric but leave it at its start value (e.g. a Summary or Histogram without any observations). See also the SummaryVec example.

Keeping the Metric for later use is possible (and should be considered if performance is critical), but keep in mind that Reset, DeleteLabelValues and Delete can be used to delete the Metric from the MetricVec. In that case, the Metric will still exist, but it will not be exported anymore, even if a Metric with the same label values is created later. See also the CounterVec example.

An error is returned if the number of label values is not the same as the number of VariableLabels in Desc.

Note that for more than one label value, this method is prone to mistakes caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as an alternative to avoid that type of mistake. For higher label numbers, the latter has a much more readable (albeit more verbose) syntax, but it comes with a performance overhead (for creating and processing the Labels map). See also the GaugeVec example.

func (*MetricVec) Reset

func (m *MetricVec) Reset()

Reset deletes all metrics in this vector.

func (*MetricVec) With

func (m *MetricVec) With(labels Labels) Metric

With works as GetMetricWith, but panics if an error occurs. The method allows neat syntax like:

httpReqs.With(Labels{"status":"404", "method":"POST"}).Inc()

func (*MetricVec) WithLabelValues

func (m *MetricVec) WithLabelValues(lvs ...string) Metric

WithLabelValues works as GetMetricWithLabelValues, but panics if an error occurs. The method allows neat syntax like:

httpReqs.WithLabelValues("404", "POST").Inc()

type MultiError

type MultiError []error

MultiError is a slice of errors implementing the error interface. It is used by a Gatherer to report multiple errors during MetricFamily gathering.

func (MultiError) Error

func (errs MultiError) Error() string

func (MultiError) MaybeUnwrap

func (errs MultiError) MaybeUnwrap() error

MaybeUnwrap returns nil if len(errs) is 0. It returns the first and only contained error as error if len(errs is 1). In all other cases, it returns the MultiError directly. This is helpful for returning a MultiError in a way that only uses the MultiError if needed.

type Observer

type Observer interface {
	Observe(float64)
}

Observer is the interface that wraps the Observe method, which is used by Histogram and Summary to add observations.

type ObserverFunc

type ObserverFunc func(float64)

The ObserverFunc type is an adapter to allow the use of ordinary functions as Observers. If f is a function with the appropriate signature, ObserverFunc(f) is an Observer that calls f.

This adapter is usually used in connection with the Timer type, and there are two general use cases:

The most common one is to use a Gauge as the Observer for a Timer. See the "Gauge" Timer example.

The more advanced use case is to create a function that dynamically decides which Observer to use for observing the duration. See the "Complex" Timer example.

func (ObserverFunc) Observe

func (f ObserverFunc) Observe(value float64)

Observe calls f(value). It implements Observer.

type ObserverVec

type ObserverVec interface {
	GetMetricWith(Labels) (Observer, error)
	GetMetricWithLabelValues(lvs ...string) (Observer, error)
	With(Labels) Observer
	WithLabelValues(...string) Observer

	Collector
}

ObserverVec is an interface implemented by `HistogramVec` and `SummaryVec`.

type Opts

type Opts struct {
	// Namespace, Subsystem, and Name are components of the fully-qualified
	// name of the Metric (created by joining these components with
	// "_"). Only Name is mandatory, the others merely help structuring the
	// name. Note that the fully-qualified name of the metric must be a
	// valid Prometheus metric name.
	Namespace string
	Subsystem string
	Name      string

	// Help provides information about this metric. Mandatory!
	//
	// Metrics with the same fully-qualified name must have the same Help
	// string.
	Help string

	// ConstLabels are used to attach fixed labels to this metric. Metrics
	// with the same fully-qualified name must have the same label names in
	// their ConstLabels.
	//
	// Note that in most cases, labels have a value that varies during the
	// lifetime of a process. Those labels are usually managed with a metric
	// vector collector (like CounterVec, GaugeVec, UntypedVec). ConstLabels
	// serve only special purposes. One is for the special case where the
	// value of a label does not change during the lifetime of a process,
	// e.g. if the revision of the running binary is put into a
	// label. Another, more advanced purpose is if more than one Collector
	// needs to collect Metrics with the same fully-qualified name. In that
	// case, those Metrics must differ in the values of their
	// ConstLabels. See the Collector examples.
	//
	// If the value of a label never changes (not even between binaries),
	// that label most likely should not be a label at all (but part of the
	// metric name).
	ConstLabels Labels
}

Opts bundles the options for creating most Metric types. Each metric implementation XXX has its own XXXOpts type, but in most cases, it is just be an alias of this type (which might change when the requirement arises.)

It is mandatory to set Name and Help to a non-empty string. All other fields are optional and can safely be left at their zero value.

type Registerer

type Registerer interface {
	// Register registers a new Collector to be included in metrics
	// collection. It returns an error if the descriptors provided by the
	// Collector are invalid or if they — in combination with descriptors of
	// already registered Collectors — do not fulfill the consistency and
	// uniqueness criteria described in the documentation of metric.Desc.
	//
	// If the provided Collector is equal to a Collector already registered
	// (which includes the case of re-registering the same Collector), the
	// returned error is an instance of AlreadyRegisteredError, which
	// contains the previously registered Collector.
	//
	// It is in general not safe to register the same Collector multiple
	// times concurrently.
	Register(Collector) error
	// MustRegister works like Register but registers any number of
	// Collectors and panics upon the first registration that causes an
	// error.
	MustRegister(...Collector)
	// Unregister unregisters the Collector that equals the Collector passed
	// in as an argument.  (Two Collectors are considered equal if their
	// Describe method yields the same set of descriptors.) The function
	// returns whether a Collector was unregistered.
	//
	// Note that even after unregistering, it will not be possible to
	// register a new Collector that is inconsistent with the unregistered
	// Collector, e.g. a Collector collecting metrics with the same name but
	// a different help string. The rationale here is that the same registry
	// instance must only collect consistent metrics throughout its
	// lifetime.
	Unregister(Collector) bool
}

Registerer is the interface for the part of a registry in charge of registering and unregistering. Users of custom registries should use Registerer as type for registration purposes (rather then the Registry type directly). In that way, they are free to use custom Registerer implementation (e.g. for testing purposes).

type Registry

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

Registry registers Prometheus collectors, collects their metrics, and gathers them into MetricFamilies for exposition. It implements both Registerer and Gatherer. The zero value is not usable. Create instances with NewRegistry or NewPedanticRegistry.

func NewPedanticRegistry

func NewPedanticRegistry() *Registry

NewPedanticRegistry returns a registry that checks during collection if each collected Metric is consistent with its reported Desc, and if the Desc has actually been registered with the registry.

Usually, a Registry will be happy as long as the union of all collected Metrics is consistent and valid even if some metrics are not consistent with their own Desc or a Desc provided by their registered Collector. Well-behaved Collectors and Metrics will only provide consistent Descs. This Registry is useful to test the implementation of Collectors and Metrics.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new vanilla Registry without any Collectors pre-registered.

func (*Registry) Gather

func (r *Registry) Gather() ([]*dto.MetricFamily, error)

Gather implements Gatherer.

func (*Registry) MustRegister

func (r *Registry) MustRegister(cs ...Collector)

MustRegister implements Registerer.

func (*Registry) Register

func (r *Registry) Register(c Collector) error

Register implements Registerer.

func (*Registry) Unregister

func (r *Registry) Unregister(c Collector) bool

Unregister implements Registerer.

type Summary

type Summary interface {
	Metric
	Collector

	// Observe adds a single observation to the summary.
	Observe(float64)
}

A Summary captures individual observations from an event or sample stream and summarizes them in a manner similar to traditional summary statistics: 1. sum of observations, 2. observation count, 3. rank estimations.

A typical use-case is the observation of request latencies. By default, a Summary provides the median, the 90th and the 99th percentile of the latency as rank estimations.

Note that the rank estimations cannot be aggregated in a meaningful way with the Prometheus query language (i.e. you cannot average or add them). If you need aggregatable quantiles (e.g. you want the 99th percentile latency of all queries served across all instances of a service), consider the Histogram metric type. See the Prometheus documentation for more details.

To create Summary instances, use NewSummary.

func NewSummary

func NewSummary(opts SummaryOpts) Summary

NewSummary creates a new Summary based on the provided SummaryOpts.

type SummaryOpts

type SummaryOpts struct {
	// Namespace, Subsystem, and Name are components of the fully-qualified
	// name of the Summary (created by joining these components with
	// "_"). Only Name is mandatory, the others merely help structuring the
	// name. Note that the fully-qualified name of the Summary must be a
	// valid Prometheus metric name.
	Namespace string
	Subsystem string
	Name      string

	// Help provides information about this Summary. Mandatory!
	//
	// Metrics with the same fully-qualified name must have the same Help
	// string.
	Help string

	// ConstLabels are used to attach fixed labels to this
	// Summary. Summaries with the same fully-qualified name must have the
	// same label names in their ConstLabels.
	//
	// Note that in most cases, labels have a value that varies during the
	// lifetime of a process. Those labels are usually managed with a
	// SummaryVec. ConstLabels serve only special purposes. One is for the
	// special case where the value of a label does not change during the
	// lifetime of a process, e.g. if the revision of the running binary is
	// put into a label. Another, more advanced purpose is if more than one
	// Collector needs to collect Summaries with the same fully-qualified
	// name. In that case, those Summaries must differ in the values of
	// their ConstLabels. See the Collector examples.
	//
	// If the value of a label never changes (not even between binaries),
	// that label most likely should not be a label at all (but part of the
	// metric name).
	ConstLabels Labels

	// Objectives defines the quantile rank estimates with their respective
	// absolute error. If Objectives[q] = e, then the value reported for q
	// will be the φ-quantile value for some φ between q-e and q+e.  The
	// default value is DefObjectives. It is used if Objectives is left at
	// its zero value (i.e. nil). To create a Summary without Objectives,
	// set it to an empty map (i.e. map[float64]float64{}).
	//
	// Deprecated: Note that the current value of DefObjectives is
	// deprecated. It will be replaced by an empty map in v0.10 of the
	// library. Please explicitly set Objectives to the desired value.
	Objectives map[float64]float64

	// MaxAge defines the duration for which an observation stays relevant
	// for the summary. Must be positive. The default value is DefMaxAge.
	MaxAge time.Duration

	// AgeBuckets is the number of buckets used to exclude observations that
	// are older than MaxAge from the summary. A higher number has a
	// resource penalty, so only increase it if the higher resolution is
	// really required. For very high observation rates, you might want to
	// reduce the number of age buckets. With only one age bucket, you will
	// effectively see a complete reset of the summary each time MaxAge has
	// passed. The default value is DefAgeBuckets.
	AgeBuckets uint32

	// BufCap defines the default sample stream buffer size.  The default
	// value of DefBufCap should suffice for most uses. If there is a need
	// to increase the value, a multiple of 500 is recommended (because that
	// is the internal buffer size of the underlying package
	// "github.com/bmizerany/perks/quantile").
	BufCap uint32
}

SummaryOpts bundles the options for creating a Summary metric. It is mandatory to set Name and Help to a non-empty string. All other fields are optional and can safely be left at their zero value.

type SummaryVec

type SummaryVec struct {
	*MetricVec
}

SummaryVec is a Collector that bundles a set of Summaries that all share the same Desc, but have different values for their variable labels. This is used if you want to count the same thing partitioned by various dimensions (e.g. HTTP request latencies, partitioned by status code and method). Create instances with NewSummaryVec.

func NewSummaryVec

func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec

NewSummaryVec creates a new SummaryVec based on the provided SummaryOpts and partitioned by the given label names. At least one label name must be provided.

func (*SummaryVec) GetMetricWith

func (m *SummaryVec) GetMetricWith(labels Labels) (Observer, error)

GetMetricWith replaces the method of the same name in MetricVec. The difference is that this method returns an Observer and not a Metric so that no type conversion to an Observer is required.

func (*SummaryVec) GetMetricWithLabelValues

func (m *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Observer, error)

GetMetricWithLabelValues replaces the method of the same name in MetricVec. The difference is that this method returns an Observer and not a Metric so that no type conversion to an Observer is required.

func (*SummaryVec) With

func (m *SummaryVec) With(labels Labels) Observer

With works as GetMetricWith, but panics where GetMetricWithLabels would have returned an error. By not returning an error, With allows shortcuts like

myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21)

func (*SummaryVec) WithLabelValues

func (m *SummaryVec) WithLabelValues(lvs ...string) Observer

WithLabelValues works as GetMetricWithLabelValues, but panics where GetMetricWithLabelValues would have returned an error. By not returning an error, WithLabelValues allows shortcuts like

myVec.WithLabelValues("404", "GET").Observe(42.21)

type Untyped deprecated

type Untyped interface {
	Metric
	Collector

	// Set sets the Untyped metric to an arbitrary value.
	Set(float64)
	// Inc increments the Untyped metric by 1.
	Inc()
	// Dec decrements the Untyped metric by 1.
	Dec()
	// Add adds the given value to the Untyped metric. (The value can be
	// negative, resulting in a decrease.)
	Add(float64)
	// Sub subtracts the given value from the Untyped metric. (The value can
	// be negative, resulting in an increase.)
	Sub(float64)
}

Untyped is a Metric that represents a single numerical value that can arbitrarily go up and down.

An Untyped metric works the same as a Gauge. The only difference is that to no type information is implied.

To create Untyped instances, use NewUntyped.

Deprecated: The Untyped type is deprecated because it doesn't make sense in direct instrumentation. If you need to mirror an external metric of unknown type (usually while writing exporters), Use MustNewConstMetric to create an untyped metric instance on the fly.

func NewUntyped

func NewUntyped(opts UntypedOpts) Untyped

NewUntyped creates a new Untyped metric from the provided UntypedOpts.

type UntypedFunc

type UntypedFunc interface {
	Metric
	Collector
}

UntypedFunc is an Untyped whose value is determined at collect time by calling a provided function.

To create UntypedFunc instances, use NewUntypedFunc.

func NewUntypedFunc

func NewUntypedFunc(opts UntypedOpts, function func() float64) UntypedFunc

NewUntypedFunc creates a new UntypedFunc based on the provided UntypedOpts. The value reported is determined by calling the given function from within the Write method. Take into account that metric collection may happen concurrently. If that results in concurrent calls to Write, like in the case where an UntypedFunc is directly registered with Prometheus, the provided function must be concurrency-safe.

type UntypedOpts

type UntypedOpts Opts

UntypedOpts is an alias for Opts. See there for doc comments.

type UntypedVec

type UntypedVec struct {
	*MetricVec
}

UntypedVec is a Collector that bundles a set of Untyped metrics that all share the same Desc, but have different values for their variable labels. This is used if you want to count the same thing partitioned by various dimensions. Create instances with NewUntypedVec.

func NewUntypedVec

func NewUntypedVec(opts UntypedOpts, labelNames []string) *UntypedVec

NewUntypedVec creates a new UntypedVec based on the provided UntypedOpts and partitioned by the given label names. At least one label name must be provided.

func (*UntypedVec) GetMetricWith

func (m *UntypedVec) GetMetricWith(labels Labels) (Untyped, error)

GetMetricWith replaces the method of the same name in MetricVec. The difference is that this method returns an Untyped and not a Metric so that no type conversion is required.

func (*UntypedVec) GetMetricWithLabelValues

func (m *UntypedVec) GetMetricWithLabelValues(lvs ...string) (Untyped, error)

GetMetricWithLabelValues replaces the method of the same name in MetricVec. The difference is that this method returns an Untyped and not a Metric so that no type conversion is required.

func (*UntypedVec) With

func (m *UntypedVec) With(labels Labels) Untyped

With works as GetMetricWith, but panics where GetMetricWithLabels would have returned an error. By not returning an error, With allows shortcuts like

myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)

func (*UntypedVec) WithLabelValues

func (m *UntypedVec) WithLabelValues(lvs ...string) Untyped

WithLabelValues works as GetMetricWithLabelValues, but panics where GetMetricWithLabelValues would have returned an error. By not returning an error, WithLabelValues allows shortcuts like

myVec.WithLabelValues("404", "GET").Add(42)

type ValueType

type ValueType int

ValueType is an enumeration of metric types that represent a simple value.

const (
	CounterValue ValueType
	GaugeValue
	UntypedValue
)

Possible values for the ValueType enum.

Jump to

Keyboard shortcuts

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