Involved Source Filesbuild_info.gocollector.gocounter.godesc.go
Package prometheus is the core instrumentation package. It provides metrics
primitives to instrument code for monitoring. It also offers a registry for
metrics. Sub-packages allow to expose the registered metrics via HTTP
(package promhttp) or push them to a Pushgateway (package push). There is
also a sub-package promauto, which provides metrics constructors with
automatic registration.
All exported functions and methods are safe to be used concurrently unless
specified otherwise.
A Basic Example
As a starting point, a very basic usage example:
package main
import (
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "cpu_temperature_celsius",
Help: "Current temperature of the CPU.",
})
hdFailures = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hd_errors_total",
Help: "Number of hard-disk errors.",
},
[]string{"device"},
)
)
func init() {
// Metrics have to be registered to be exposed:
prometheus.MustRegister(cpuTemp)
prometheus.MustRegister(hdFailures)
}
func main() {
cpuTemp.Set(65.3)
hdFailures.With(prometheus.Labels{"device":"/dev/sda"}).Inc()
// The Handler function provides a default handler to expose metrics
// via an HTTP server. "/metrics" is the usual endpoint for that.
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
}
This is a complete program that exports two metrics, a Gauge and a Counter,
the latter with a label attached to turn it into a (one-dimensional) vector.
Metrics
The number of exported identifiers in this package might appear a bit
overwhelming. However, in addition to the basic plumbing shown in the example
above, you only need to understand the different metric types and their
vector versions for basic usage. Furthermore, if you are not concerned with
fine-grained control of when and how to register metrics with the registry,
have a look at the promauto package, which will effectively allow you to
ignore registration altogether in simple cases.
Above, you have already touched the Counter and the Gauge. There are two more
advanced metric types: the Summary and Histogram. A more thorough description
of those four metric types can be found in the Prometheus docs:
https://prometheus.io/docs/concepts/metric_types/
A fifth "type" of metric is Untyped. It behaves like a Gauge, but signals the
Prometheus server not to assume anything about its type.
In addition to the fundamental metric types Gauge, Counter, Summary,
Histogram, and Untyped, a very important part of the Prometheus data model is
the partitioning of samples along dimensions called labels, which results in
metric vectors. The fundamental types are GaugeVec, CounterVec, SummaryVec,
HistogramVec, and UntypedVec.
While only the fundamental metric types implement the Metric interface, both
the metrics and their vector versions implement the Collector interface. A
Collector manages the collection of a number of Metrics, but for convenience,
a Metric can also “collect itself”. Note that Gauge, Counter, Summary,
Histogram, and Untyped are interfaces themselves while GaugeVec, CounterVec,
SummaryVec, HistogramVec, and UntypedVec are not.
To create instances of Metrics and their vector versions, you need a suitable
…Opts struct, i.e. GaugeOpts, CounterOpts, SummaryOpts, HistogramOpts, or
UntypedOpts.
Custom Collectors and constant Metrics
While you could create your own implementations of Metric, most likely you
will only ever implement the Collector interface on your own. At a first
glance, a custom Collector seems handy to bundle Metrics for common
registration (with the prime example of the different metric vectors above,
which bundle all the metrics of the same name but with different labels).
There is a more involved use case, too: If you already have metrics
available, created outside of the Prometheus context, you don't need the
interface of the various Metric types. You essentially want to mirror the
existing numbers into Prometheus Metrics during collection. An own
implementation of the Collector interface is perfect for that. You can create
Metric instances “on the fly” using NewConstMetric, NewConstHistogram, and
NewConstSummary (and their respective Must… versions). That will happen in
the Collect method. The Describe method has to return separate Desc
instances, representative of the “throw-away” metrics to be created later.
NewDesc comes in handy to create those Desc instances. Alternatively, you
could return no Desc at all, which will mark the Collector “unchecked”. No
checks are performed at registration time, but metric consistency will still
be ensured at scrape time, i.e. any inconsistencies will lead to scrape
errors. Thus, with unchecked Collectors, the responsibility to not collect
metrics that lead to inconsistencies in the total scrape result lies with the
implementer of the Collector. While this is not a desirable state, it is
sometimes necessary. The typical use case is a situation where the exact
metrics to be returned by a Collector cannot be predicted at registration
time, but the implementer has sufficient knowledge of the whole system to
guarantee metric consistency.
The Collector example illustrates the use case. You can also look at the
source code of the processCollector (mirroring process metrics), the
goCollector (mirroring Go metrics), or the expvarCollector (mirroring expvar
metrics) as examples that are used in this package itself.
If you just need to call a function to get a single float value to collect as
a metric, GaugeFunc, CounterFunc, or UntypedFunc might be interesting
shortcuts.
Advanced Uses of the Registry
While MustRegister is the by far most common way of registering a Collector,
sometimes you might want to handle the errors the registration might cause.
As suggested by the name, MustRegister panics if an error occurs. With the
Register function, the error is returned and can be handled.
An error is returned if the registered Collector is incompatible or
inconsistent with already registered metrics. The registry aims for
consistency of the collected metrics according to the Prometheus data model.
Inconsistencies are ideally detected at registration time, not at collect
time. The former will usually be detected at start-up time of a program,
while the latter will only happen at scrape time, possibly not even on the
first scrape if the inconsistency only becomes relevant later. That is the
main reason why a Collector and a Metric have to describe themselves to the
registry.
So far, everything we did operated on the so-called default registry, as it
can be found in the global DefaultRegisterer variable. With NewRegistry, you
can create a custom registry, or you can even implement the Registerer or
Gatherer interfaces yourself. The methods Register and Unregister work in the
same way on a custom registry as the global functions Register and Unregister
on the default registry.
There are a number of uses for custom registries: You can use registries with
special properties, see NewPedanticRegistry. You can avoid global state, as
it is imposed by the DefaultRegisterer. You can use multiple registries at
the same time to expose different metrics in different ways. You can use
separate registries for testing purposes.
Also note that the DefaultRegisterer comes registered with a Collector for Go
runtime metrics (via NewGoCollector) and a Collector for process metrics (via
NewProcessCollector). With a custom registry, you are in control and decide
yourself about the Collectors to register.
HTTP Exposition
The Registry implements the Gatherer interface. The caller of the Gather
method can then expose the gathered metrics in some way. Usually, the metrics
are served via HTTP on the /metrics endpoint. That's happening in the example
above. The tools to expose metrics via HTTP are in the promhttp sub-package.
Pushing to the Pushgateway
Function for pushing to the Pushgateway can be found in the push sub-package.
Graphite Bridge
Functions and examples to push metrics from a Gatherer to Graphite can be
found in the graphite sub-package.
Other Means of Exposition
More ways of exposing metrics can easily be added by following the approaches
of the existing implementations.
expvar_collector.gofnv.gogauge.gogo_collector.gohistogram.golabels.gometric.goobserver.goprocess_collector.goprocess_collector_other.goregistry.gosummary.gotimer.gountyped.govalue.govec.gowrap.go
Code Examples
package main
import (
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// ClusterManager is an example for a system that might have been built without
// Prometheus in mind. It models a central manager of jobs running in a
// cluster. Thus, we implement a custom Collector called
// ClusterManagerCollector, which collects information from a ClusterManager
// using its provided methods and turns them into Prometheus Metrics for
// collection.
//
// An additional challenge is that multiple instances of the ClusterManager are
// run within the same binary, each in charge of a different zone. We need to
// make use of wrapping Registerers to be able to register each
// ClusterManagerCollector instance with Prometheus.
type ClusterManager struct {
Zone string
// Contains many more fields not listed in this example.
}
// ReallyExpensiveAssessmentOfTheSystemState is a mock for the data gathering a
// real cluster manager would have to do. Since it may actually be really
// expensive, it must only be called once per collection. This implementation,
// obviously, only returns some made-up data.
func (c *ClusterManager) ReallyExpensiveAssessmentOfTheSystemState() (
oomCountByHost map[string]int, ramUsageByHost map[string]float64,
) {
// Just example fake data.
oomCountByHost = map[string]int{
"foo.example.org": 42,
"bar.example.org": 2001,
}
ramUsageByHost = map[string]float64{
"foo.example.org": 6.023e23,
"bar.example.org": 3.14,
}
return
}
// ClusterManagerCollector implements the Collector interface.
type ClusterManagerCollector struct {
ClusterManager *ClusterManager
}
// Descriptors used by the ClusterManagerCollector below.
var (
oomCountDesc = prometheus.NewDesc(
"clustermanager_oom_crashes_total",
"Number of OOM crashes.",
[]string{"host"}, nil,
)
ramUsageDesc = prometheus.NewDesc(
"clustermanager_ram_usage_bytes",
"RAM usage as reported to the cluster manager.",
[]string{"host"}, nil,
)
)
// Describe is implemented with DescribeByCollect. That's possible because the
// Collect method will always return the same two metrics with the same two
// descriptors.
func (cc ClusterManagerCollector) Describe(ch chan<- *prometheus.Desc) {
prometheus.DescribeByCollect(cc, ch)
}
// Collect first triggers the ReallyExpensiveAssessmentOfTheSystemState. Then it
// creates constant metrics for each host on the fly based on the returned data.
//
// Note that Collect could be called concurrently, so we depend on
// ReallyExpensiveAssessmentOfTheSystemState to be concurrency-safe.
func (cc ClusterManagerCollector) Collect(ch chan<- prometheus.Metric) {
oomCountByHost, ramUsageByHost := cc.ClusterManager.ReallyExpensiveAssessmentOfTheSystemState()
for host, oomCount := range oomCountByHost {
ch <- prometheus.MustNewConstMetric(
oomCountDesc,
prometheus.CounterValue,
float64(oomCount),
host,
)
}
for host, ramUsage := range ramUsageByHost {
ch <- prometheus.MustNewConstMetric(
ramUsageDesc,
prometheus.GaugeValue,
ramUsage,
host,
)
}
}
// NewClusterManager first creates a Prometheus-ignorant ClusterManager
// instance. Then, it creates a ClusterManagerCollector for the just created
// ClusterManager. Finally, it registers the ClusterManagerCollector with a
// wrapping Registerer that adds the zone as a label. In this way, the metrics
// collected by different ClusterManagerCollectors do not collide.
func NewClusterManager(zone string, reg prometheus.Registerer) *ClusterManager {
c := &ClusterManager{
Zone: zone,
}
cc := ClusterManagerCollector{ClusterManager: c}
prometheus.WrapRegistererWith(prometheus.Labels{"zone": zone}, reg).MustRegister(cc)
return c
}
func main() {
// Since we are dealing with custom Collector implementations, it might
// be a good idea to try it out with a pedantic registry.
reg := prometheus.NewPedanticRegistry()
// Construct cluster managers. In real code, we would assign them to
// variables to then do something with them.
NewClusterManager("db", reg)
NewClusterManager("ca", reg)
// Add the standard process and Go metrics to the custom registry.
reg.MustRegister(
prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}),
prometheus.NewGoCollector(),
)
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
log.Fatal(http.ListenAndServe(":8080", nil))
}
package main
import (
"math/rand"
"time"
"github.com/prometheus/client_golang/prometheus"
)
var (
requestDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "example_request_duration_seconds",
Help: "Histogram for the runtime of a simple example function.",
Buckets: prometheus.LinearBuckets(0.01, 0.01, 10),
})
)
func main() {
// timer times this example function. It uses a Histogram, but a Summary
// would also work, as both implement Observer. Check out
// https://prometheus.io/docs/practices/histograms/ for differences.
timer := prometheus.NewTimer(requestDuration)
defer timer.ObserveDuration()
// Do something here that takes time.
time.Sleep(time.Duration(rand.NormFloat64()*10000+50000) * time.Microsecond)
}
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
)
var (
// apiRequestDuration tracks the duration separate for each HTTP status
// class (1xx, 2xx, ...). This creates a fair amount of time series on
// the Prometheus server. Usually, you would track the duration of
// serving HTTP request without partitioning by outcome. Do something
// like this only if needed. Also note how only status classes are
// tracked, not every single status code. The latter would create an
// even larger amount of time series. Request counters partitioned by
// status code are usually OK as each counter only creates one time
// series. Histograms are way more expensive, so partition with care and
// only where you really need separate latency tracking. Partitioning by
// status class is only an example. In concrete cases, other partitions
// might make more sense.
apiRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "api_request_duration_seconds",
Help: "Histogram for the request duration of the public API, partitioned by status class.",
Buckets: prometheus.ExponentialBuckets(0.1, 1.5, 5),
},
[]string{"status_class"},
)
)
func handler(w http.ResponseWriter, r *http.Request) {
status := http.StatusOK
// The ObserverFunc gets called by the deferred ObserveDuration and
// decides which Histogram's Observe method is called.
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
switch {
case status >= 500: // Server error.
apiRequestDuration.WithLabelValues("5xx").Observe(v)
case status >= 400: // Client error.
apiRequestDuration.WithLabelValues("4xx").Observe(v)
case status >= 300: // Redirection.
apiRequestDuration.WithLabelValues("3xx").Observe(v)
case status >= 200: // Success.
apiRequestDuration.WithLabelValues("2xx").Observe(v)
default: // Informational.
apiRequestDuration.WithLabelValues("1xx").Observe(v)
}
}))
defer timer.ObserveDuration()
// Handle the request. Set status accordingly.
// ...
}
func main() {
http.HandleFunc("/api", handler)
}
package main
import (
"os"
"github.com/prometheus/client_golang/prometheus"
)
var (
// If a function is called rarely (i.e. not more often than scrapes
// happen) or ideally only once (like in a batch job), it can make sense
// to use a Gauge for timing the function call. For timing a batch job
// and pushing the result to a Pushgateway, see also the comprehensive
// example in the push package.
funcDuration = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "example_function_duration_seconds",
Help: "Duration of the last call of an example function.",
})
)
func run() error {
// The Set method of the Gauge is used to observe the duration.
timer := prometheus.NewTimer(prometheus.ObserverFunc(funcDuration.Set))
defer timer.ObserveDuration()
// Do something. Return errors as encountered. The use of 'defer' above
// makes sure the function is still timed properly.
return nil
}
func main() {
if err := run(); err != nil {
os.Exit(1)
}
}
Package-Level Type Names (total 62, in which 34 are exported)
/* sort exporteds by: | */
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.
ExistingCollectorCollectorNewCollectorCollector( T) Error() string
T : error
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.
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
(unless the Collector is unchecked, see above). 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.
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.
Sending no descriptor at all marks the Collector as “unchecked”,
i.e. no checks will be performed at registration time, and the
Collector may yield any Metric it sees fit in its Collect method.
This method idempotently sends the same descriptors throughout the
lifetime of the Collector. It may be called concurrently and
therefore must be implemented in a concurrency safe way.
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.
Counter(interface)CounterFunc(interface)CounterVecGauge(interface)GaugeFunc(interface)GaugeVecHistogram(interface)HistogramVecObserverVec(interface)Summary(interface)SummaryVecUntypedFunc(interface)
*counter
*expvarCollector
*gauge
*goCollector
*histogram
*metricMapmetricVec
*noObjectivesSummary
*processCollector
*selfCollector
*summary
*valueFunc
*wrappingCollector
*contrib.go.opencensus.io/exporter/prometheus.collector
func NewBuildInfoCollector() Collector
func NewExpvarCollector(exports map[string]*Desc) Collector
func NewGoCollector() Collector
func NewProcessCollector(opts ProcessCollectorOpts) Collector
func DescribeByCollect(c Collector, descs chan<- *Desc)
func MustRegister(cs ...Collector)
func Register(c Collector) error
func Unregister(c Collector) bool
func Registerer.MustRegister(...Collector)
func Registerer.Register(Collector) error
func Registerer.Unregister(Collector) bool
func (*Registry).MustRegister(cs ...Collector)
func (*Registry).Register(c Collector) error
func (*Registry).Unregister(c Collector) bool
func github.com/prometheus/client_golang/prometheus/promhttp.checkLabels(c Collector) (code bool, method bool)
func github.com/prometheus/client_golang/prometheus/promhttp.isLabelCurried(c Collector, label string) bool
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.
Add adds the given value to the counter. It panics if the value is <
0.
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
(unless the Collector is unchecked, see above). 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.
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).
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.
Sending no descriptor at all marks the Collector as “unchecked”,
i.e. no checks will be performed at registration time, and the
Collector may yield any Metric it sees fit in its Collect method.
This method idempotently sends the same descriptors throughout the
lifetime of the Collector. It may be called concurrently and
therefore must be implemented in a concurrency safe way.
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.
Inc increments the counter by 1. Use Add to increment it by arbitrary
non-negative values.
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. Callers of Write should
still make sure of sorting if they depend on it.
Gauge(interface)
*counter
*gauge
T : Collector
T : CounterFunc
T : GaugeFunc
T : Metric
T : UntypedFunc
func NewCounter(opts CounterOpts) Counter
func (*CounterVec).GetMetricWith(labels Labels) (Counter, error)
func (*CounterVec).GetMetricWithLabelValues(lvs ...string) (Counter, error)
func (*CounterVec).With(labels Labels) Counter
func (*CounterVec).WithLabelValues(lvs ...string) Counter
CounterFunc is a Counter whose value is determined at collect time by calling a
provided function.
To create CounterFunc instances, use NewCounterFunc.
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
(unless the Collector is unchecked, see above). 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.
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).
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.
Sending no descriptor at all marks the Collector as “unchecked”,
i.e. no checks will be performed at registration time, and the
Collector may yield any Metric it sees fit in its Collect method.
This method idempotently sends the same descriptors throughout the
lifetime of the Collector. It may be called concurrently and
therefore must be implemented in a concurrency safe way.
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.
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. Callers of Write should
still make sure of sorting if they depend on it.
Counter(interface)Gauge(interface)GaugeFunc(interface)Histogram(interface)Summary(interface)UntypedFunc(interface)
*counter
*gauge
*histogram
*noObjectivesSummary
*summary
*valueFunc
T : Collector
T : GaugeFunc
T : Metric
T : UntypedFunc
func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc
CounterOpts is an alias for Opts. See there for doc comments.
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.
ConstLabels are only used rarely. In particular, do not use them to
attach the same labels to all your metrics. Those use cases are
better covered by target labels set by the scraping Prometheus
server, or by one specific metric (e.g. a build_info or a
machine_role metric). See also
https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels
Help provides information about this metric.
Metrics with the same fully-qualified name must have the same Help
string.
Namestring
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.
Subsystemstring
func NewCounter(opts CounterOpts) Counter
func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc
func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec
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.
metricVec*metricVecmetricVec.curry[]curriedLabelValue
hashAdd and hashAddByte can be replaced for testing collision handling.
metricVec.hashAddBytefunc(h uint64, b byte) uint64metricVec.metricMap*metricMapmetricVec.metricMap.desc*DescmetricVec.metricMap.metricsmap[uint64][]metricWithLabelValues
// Protects metrics.
metricVec.metricMap.newMetricfunc(labelValues ...string) Metric
Collect implements Collector.
CurryWith returns a vector curried with the provided labels, i.e. the
returned vector has those labels pre-set for all labeled operations performed
on it. The cardinality of the curried vector is reduced accordingly. The
order of the remaining labels stays the same (just with the curried labels
taken out of the sequence – which is relevant for the
(GetMetric)WithLabelValues methods). It is possible to curry a curried
vector, but only with labels not yet used for currying before.
The metrics contained in the CounterVec are shared between the curried and
uncurried vectors. They are just accessed differently. Curried and uncurried
vectors behave identically in terms of collection. Only one must be
registered with a given registry (usually the uncurried version). The Reset
method deletes all metrics, even if called on a curried vector.
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 Desc. 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.
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.
Describe implements Collector. It will send exactly one Desc to the provided
channel.
GetMetricWith returns the Counter 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 Counter is created. Implications of
creating a Counter without using it and keeping the Counter 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 (minus any curried labels).
This method is used for the same purpose as
GetMetricWithLabelValues(...string). See there for pros and cons of the two
methods.
GetMetricWithLabelValues returns the Counter 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 Counter is created.
It is possible to call this method without using the returned Counter to only
create the new Counter but leave it at its starting value 0. See also the
SummaryVec example.
Keeping the Counter 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 Counter from the CounterVec. In that case,
the Counter will still exist, but it will not be exported anymore, even if a
Counter with the same label values is created later.
An error is returned if the number of label values is not the same as the
number of VariableLabels in Desc (minus any curried labels).
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.
MustCurryWith works as CurryWith but panics where CurryWith would have
returned an error.
Reset deletes all metrics in this vector.
With works as GetMetricWith, but panics where GetMetricWithLabels would have
returned an error. Not returning an error allows shortcuts like
myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Add(42)
WithLabelValues works as GetMetricWithLabelValues, but panics where
GetMetricWithLabelValues would have returned an error. Not returning an
error allows shortcuts like
myVec.WithLabelValues("404", "GET").Add(42)
( T) curryWith(labels Labels) (*metricVec, error)
deleteByHashWithLabelValues removes the metric from the hash bucket h. If
there are multiple matches in the bucket, use lvs to select a metric and
remove only that metric.
deleteByHashWithLabels removes the metric from the hash bucket h. If there
are multiple matches in the bucket, use lvs to select a metric and remove
only that metric.
( T) getMetricWith(labels Labels) (Metric, error)
getMetricWithHashAndLabelValues gets a metric while handling possible
collisions in the hash space. Must be called while holding the read mutex.
getMetricWithHashAndLabels gets a metric while handling possible collisions in
the hash space. Must be called while holding read mutex.
( T) getMetricWithLabelValues(lvs ...string) (Metric, error)
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
( T) hashLabelValues(vals []string) (uint64, error)( T) hashLabels(labels Labels) (uint64, error)
T : Collector
func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec
func (*CounterVec).CurryWith(labels Labels) (*CounterVec, error)
func (*CounterVec).MustCurryWith(labels Labels) *CounterVec
func github.com/prometheus/client_golang/prometheus/promhttp.InstrumentHandlerCounter(counter *CounterVec, next http.Handler) http.HandlerFunc
func github.com/prometheus/client_golang/prometheus/promhttp.InstrumentRoundTripperCounter(counter *CounterVec, next http.RoundTripper) promhttp.RoundTripperFunc
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.
Gather calls the Collect method of the registered Collectors and then
gathers the collected metrics into a lexicographically sorted slice
of uniquely named MetricFamily protobufs. Gather ensures that the
returned slice is valid and self-consistent so that it can be used
for valid exposition. As an exception to the strict consistency
requirements described for metric.Desc, Gather will tolerate
different sets of label names for metrics of the same metric family.
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. Note that this is mostly useful for
debugging purposes. If the gathered protobufs are to be used for
exposition in actual monitoring, it is almost always better to not
expose an incomplete result and instead disregard the returned
MetricFamily protobufs in case the returned error is non-nil.
GathererFuncGatherers
*Registry
func WriteToTextfile(filename string, g Gatherer) error
func github.com/prometheus/client_golang/prometheus/promhttp.HandlerFor(reg Gatherer, opts promhttp.HandlerOpts) http.Handler
var DefaultGatherer
GathererFunc turns a function into a Gatherer.
Gather implements Gatherer.
T : 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 calls 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.
Gather implements Gatherer.
T : Gatherer
Gauge is a Metric that represents a single numerical value that can
arbitrarily go up and down.
A Gauge is typically used for measured values like temperatures or current
memory usage, but also "counts" that can go up and down, like the number of
running goroutines.
To create Gauge instances, use NewGauge.
Add adds the given value to the Gauge. (The value can be negative,
resulting in a decrease of the Gauge.)
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
(unless the Collector is unchecked, see above). 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.
Dec decrements the Gauge by 1. Use Sub to decrement it by arbitrary
values.
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).
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.
Sending no descriptor at all marks the Collector as “unchecked”,
i.e. no checks will be performed at registration time, and the
Collector may yield any Metric it sees fit in its Collect method.
This method idempotently sends the same descriptors throughout the
lifetime of the Collector. It may be called concurrently and
therefore must be implemented in a concurrency safe way.
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.
Inc increments the Gauge by 1. Use Add to increment it by arbitrary
values.
Set sets the Gauge to an arbitrary value.
SetToCurrentTime sets the Gauge to the current Unix time in seconds.
Sub subtracts the given value from the Gauge. (The value can be
negative, resulting in an increase of the Gauge.)
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. Callers of Write should
still make sure of sorting if they depend on it.
*gauge
T : Collector
T : Counter
T : CounterFunc
T : GaugeFunc
T : Metric
T : UntypedFunc
func NewGauge(opts GaugeOpts) Gauge
func (*GaugeVec).GetMetricWith(labels Labels) (Gauge, error)
func (*GaugeVec).GetMetricWithLabelValues(lvs ...string) (Gauge, error)
func (*GaugeVec).With(labels Labels) Gauge
func (*GaugeVec).WithLabelValues(lvs ...string) Gauge
func github.com/prometheus/client_golang/prometheus/promhttp.InstrumentHandlerInFlight(g Gauge, next http.Handler) http.Handler
func github.com/prometheus/client_golang/prometheus/promhttp.InstrumentRoundTripperInFlight(gauge Gauge, next http.RoundTripper) promhttp.RoundTripperFunc
GaugeFunc is a Gauge whose value is determined at collect time by calling a
provided function.
To create GaugeFunc instances, use NewGaugeFunc.
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
(unless the Collector is unchecked, see above). 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.
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).
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.
Sending no descriptor at all marks the Collector as “unchecked”,
i.e. no checks will be performed at registration time, and the
Collector may yield any Metric it sees fit in its Collect method.
This method idempotently sends the same descriptors throughout the
lifetime of the Collector. It may be called concurrently and
therefore must be implemented in a concurrency safe way.
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.
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. Callers of Write should
still make sure of sorting if they depend on it.
Counter(interface)CounterFunc(interface)Gauge(interface)Histogram(interface)Summary(interface)UntypedFunc(interface)
*counter
*gauge
*histogram
*noObjectivesSummary
*summary
*valueFunc
T : Collector
T : CounterFunc
T : Metric
T : UntypedFunc
func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc
GaugeOpts is an alias for Opts. See there for doc comments.
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.
ConstLabels are only used rarely. In particular, do not use them to
attach the same labels to all your metrics. Those use cases are
better covered by target labels set by the scraping Prometheus
server, or by one specific metric (e.g. a build_info or a
machine_role metric). See also
https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels
Help provides information about this metric.
Metrics with the same fully-qualified name must have the same Help
string.
Namestring
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.
Subsystemstring
func NewGauge(opts GaugeOpts) Gauge
func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc
func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec
GaugeVec is a Collector that bundles a set of Gauges 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 operations queued, partitioned by user and operation
type). Create instances with NewGaugeVec.
metricVec*metricVecmetricVec.curry[]curriedLabelValue
hashAdd and hashAddByte can be replaced for testing collision handling.
metricVec.hashAddBytefunc(h uint64, b byte) uint64metricVec.metricMap*metricMapmetricVec.metricMap.desc*DescmetricVec.metricMap.metricsmap[uint64][]metricWithLabelValues
// Protects metrics.
metricVec.metricMap.newMetricfunc(labelValues ...string) Metric
Collect implements Collector.
CurryWith returns a vector curried with the provided labels, i.e. the
returned vector has those labels pre-set for all labeled operations performed
on it. The cardinality of the curried vector is reduced accordingly. The
order of the remaining labels stays the same (just with the curried labels
taken out of the sequence – which is relevant for the
(GetMetric)WithLabelValues methods). It is possible to curry a curried
vector, but only with labels not yet used for currying before.
The metrics contained in the GaugeVec are shared between the curried and
uncurried vectors. They are just accessed differently. Curried and uncurried
vectors behave identically in terms of collection. Only one must be
registered with a given registry (usually the uncurried version). The Reset
method deletes all metrics, even if called on a curried vector.
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 Desc. 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.
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.
Describe implements Collector. It will send exactly one Desc to the provided
channel.
GetMetricWith returns the Gauge 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 Gauge is created. Implications of
creating a Gauge without using it and keeping the Gauge 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 (minus any curried labels).
This method is used for the same purpose as
GetMetricWithLabelValues(...string). See there for pros and cons of the two
methods.
GetMetricWithLabelValues returns the Gauge 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 Gauge is created.
It is possible to call this method without using the returned Gauge to only
create the new Gauge but leave it at its starting value 0. See also the
SummaryVec example.
Keeping the Gauge 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 Gauge from the GaugeVec. In that case, the
Gauge will still exist, but it will not be exported anymore, even if a
Gauge 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 (minus any curried labels).
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).
MustCurryWith works as CurryWith but panics where CurryWith would have
returned an error.
Reset deletes all metrics in this vector.
With works as GetMetricWith, but panics where GetMetricWithLabels would have
returned an error. Not returning an error allows shortcuts like
myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Add(42)
WithLabelValues works as GetMetricWithLabelValues, but panics where
GetMetricWithLabelValues would have returned an error. Not returning an
error allows shortcuts like
myVec.WithLabelValues("404", "GET").Add(42)
( T) curryWith(labels Labels) (*metricVec, error)
deleteByHashWithLabelValues removes the metric from the hash bucket h. If
there are multiple matches in the bucket, use lvs to select a metric and
remove only that metric.
deleteByHashWithLabels removes the metric from the hash bucket h. If there
are multiple matches in the bucket, use lvs to select a metric and remove
only that metric.
( T) getMetricWith(labels Labels) (Metric, error)
getMetricWithHashAndLabelValues gets a metric while handling possible
collisions in the hash space. Must be called while holding the read mutex.
getMetricWithHashAndLabels gets a metric while handling possible collisions in
the hash space. Must be called while holding read mutex.
( T) getMetricWithLabelValues(lvs ...string) (Metric, error)
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
( T) hashLabelValues(vals []string) (uint64, error)( T) hashLabels(labels Labels) (uint64, error)
T : Collector
func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec
func (*GaugeVec).CurryWith(labels Labels) (*GaugeVec, error)
func (*GaugeVec).MustCurryWith(labels Labels) *GaugeVec
A Histogram counts individual observations from an event or sample stream in
configurable buckets. Similar to a summary, it also provides a sum of
observations and an observation count.
On the Prometheus server, quantiles can be calculated from a Histogram using
the histogram_quantile function in the query language.
Note that Histograms, in contrast to Summaries, can be aggregated with the
Prometheus query language (see the documentation for detailed
procedures). However, Histograms require the user to pre-define suitable
buckets, and they are in general less accurate. The Observe method of a
Histogram has a very low performance overhead in comparison with the Observe
method of a Summary.
To create Histogram instances, use NewHistogram.
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
(unless the Collector is unchecked, see above). 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.
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).
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.
Sending no descriptor at all marks the Collector as “unchecked”,
i.e. no checks will be performed at registration time, and the
Collector may yield any Metric it sees fit in its Collect method.
This method idempotently sends the same descriptors throughout the
lifetime of the Collector. It may be called concurrently and
therefore must be implemented in a concurrency safe way.
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.
Observe adds a single observation to the histogram.
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. Callers of Write should
still make sure of sorting if they depend on it.
Summary(interface)
*histogram
*noObjectivesSummary
*summary
T : Collector
T : CounterFunc
T : GaugeFunc
T : Metric
T : Observer
T : Summary
T : UntypedFunc
func NewHistogram(opts HistogramOpts) Histogram
func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogram
HistogramOpts bundles the options for creating a Histogram metric. It is
mandatory to set Name to a non-empty string. All other fields are optional
and can safely be left at their zero value, although it is strongly
encouraged to set a Help string.
Buckets defines the buckets into which observations are counted. Each
element in the slice is the upper inclusive bound of a bucket. The
values must be sorted in strictly increasing order. There is no need
to add a highest bucket with +Inf bound, it will be added
implicitly. The default value is DefBuckets.
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.
ConstLabels are only used rarely. In particular, do not use them to
attach the same labels to all your metrics. Those use cases are
better covered by target labels set by the scraping Prometheus
server, or by one specific metric (e.g. a build_info or a
machine_role metric). See also
https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels-not-static-scraped-labels
Help provides information about this Histogram.
Metrics with the same fully-qualified name must have the same Help
string.
Namestring
Namespace, Subsystem, and Name are components of the fully-qualified
name of the Histogram (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 Histogram must be a
valid Prometheus metric name.
Subsystemstring
func NewHistogram(opts HistogramOpts) Histogram
func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec
func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogram
HistogramVec is a Collector that bundles a set of Histograms 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 NewHistogramVec.
metricVec*metricVecmetricVec.curry[]curriedLabelValue
hashAdd and hashAddByte can be replaced for testing collision handling.
metricVec.hashAddBytefunc(h uint64, b byte) uint64metricVec.metricMap*metricMapmetricVec.metricMap.desc*DescmetricVec.metricMap.metricsmap[uint64][]metricWithLabelValues
// Protects metrics.
metricVec.metricMap.newMetricfunc(labelValues ...string) Metric
Collect implements Collector.
CurryWith returns a vector curried with the provided labels, i.e. the
returned vector has those labels pre-set for all labeled operations performed
on it. The cardinality of the curried vector is reduced accordingly. The
order of the remaining labels stays the same (just with the curried labels
taken out of the sequence – which is relevant for the
(GetMetric)WithLabelValues methods). It is possible to curry a curried
vector, but only with labels not yet used for currying before.
The metrics contained in the HistogramVec are shared between the curried and
uncurried vectors. They are just accessed differently. Curried and uncurried
vectors behave identically in terms of collection. Only one must be
registered with a given registry (usually the uncurried version). The Reset
method deletes all metrics, even if called on a curried vector.
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 Desc. 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.
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.
Describe implements Collector. It will send exactly one Desc to the provided
channel.
GetMetricWith returns the Histogram 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 Histogram is created. Implications of
creating a Histogram without using it and keeping the Histogram 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 (minus any curried labels).
This method is used for the same purpose as
GetMetricWithLabelValues(...string). See there for pros and cons of the two
methods.
GetMetricWithLabelValues returns the Histogram 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 Histogram is created.
It is possible to call this method without using the returned Histogram to only
create the new Histogram but leave it at its starting value, a Histogram without
any observations.
Keeping the Histogram 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 Histogram from the HistogramVec. In that case, the
Histogram will still exist, but it will not be exported anymore, even if a
Histogram 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 (minus any curried labels).
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.
MustCurryWith works as CurryWith but panics where CurryWith would have
returned an error.
Reset deletes all metrics in this vector.
With works as GetMetricWith but panics where GetMetricWithLabels would have
returned an error. Not returning an error allows shortcuts like
myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Observe(42.21)
WithLabelValues works as GetMetricWithLabelValues, but panics where
GetMetricWithLabelValues would have returned an error. Not returning an
error allows shortcuts like
myVec.WithLabelValues("404", "GET").Observe(42.21)
( T) curryWith(labels Labels) (*metricVec, error)
deleteByHashWithLabelValues removes the metric from the hash bucket h. If
there are multiple matches in the bucket, use lvs to select a metric and
remove only that metric.
deleteByHashWithLabels removes the metric from the hash bucket h. If there
are multiple matches in the bucket, use lvs to select a metric and remove
only that metric.
( T) getMetricWith(labels Labels) (Metric, error)
getMetricWithHashAndLabelValues gets a metric while handling possible
collisions in the hash space. Must be called while holding the read mutex.
getMetricWithHashAndLabels gets a metric while handling possible collisions in
the hash space. Must be called while holding read mutex.
( T) getMetricWithLabelValues(lvs ...string) (Metric, error)
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
( T) hashLabelValues(vals []string) (uint64, error)( T) hashLabels(labels Labels) (uint64, error)
T : Collector
*T : ObserverVec
func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec
MultiError is a slice of errors implementing the error interface. It is used
by a Gatherer to report multiple errors during MetricFamily gathering.
Append appends the provided error if it is not nil.
( T) Error() string
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.
T : error
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.
Observe calls f(value). It implements Observer.
T : Observer
ObserverVec is an interface implemented by `HistogramVec` and `SummaryVec`.
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
(unless the Collector is unchecked, see above). 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.
( T) CurryWith(Labels) (ObserverVec, error)
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.
Sending no descriptor at all marks the Collector as “unchecked”,
i.e. no checks will be performed at registration time, and the
Collector may yield any Metric it sees fit in its Collect method.
This method idempotently sends the same descriptors throughout the
lifetime of the Collector. It may be called concurrently and
therefore must be implemented in a concurrency safe way.
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.
( T) GetMetricWith(Labels) (Observer, error)( T) GetMetricWithLabelValues(lvs ...string) (Observer, error)( T) MustCurryWith(Labels) ObserverVec( T) With(Labels) Observer( T) WithLabelValues(...string) Observer
*HistogramVec
*SummaryVec
T : Collector
func (*HistogramVec).CurryWith(labels Labels) (ObserverVec, error)
func (*HistogramVec).MustCurryWith(labels Labels) ObserverVec
func ObserverVec.CurryWith(Labels) (ObserverVec, error)
func ObserverVec.MustCurryWith(Labels) ObserverVec
func (*SummaryVec).CurryWith(labels Labels) (ObserverVec, error)
func (*SummaryVec).MustCurryWith(labels Labels) ObserverVec
func github.com/prometheus/client_golang/prometheus/promhttp.InstrumentHandlerDuration(obs ObserverVec, next http.Handler) http.HandlerFunc
func github.com/prometheus/client_golang/prometheus/promhttp.InstrumentHandlerRequestSize(obs ObserverVec, next http.Handler) http.HandlerFunc
func github.com/prometheus/client_golang/prometheus/promhttp.InstrumentHandlerResponseSize(obs ObserverVec, next http.Handler) http.Handler
func github.com/prometheus/client_golang/prometheus/promhttp.InstrumentHandlerTimeToWriteHeader(obs ObserverVec, next http.Handler) http.HandlerFunc
func github.com/prometheus/client_golang/prometheus/promhttp.InstrumentRoundTripperDuration(obs ObserverVec, next http.RoundTripper) promhttp.RoundTripperFunc
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 to a non-empty string. All other fields are
optional and can safely be left at their zero value, although it is strongly
encouraged to set a 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.
ConstLabels are only used rarely. In particular, do not use them to
attach the same labels to all your metrics. Those use cases are
better covered by target labels set by the scraping Prometheus
server, or by one specific metric (e.g. a build_info or a
machine_role metric). See also
https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels
Help provides information about this metric.
Metrics with the same fully-qualified name must have the same Help
string.
Namestring
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.
Subsystemstring
ProcessCollectorOpts defines the behavior of a process metrics collector
created with NewProcessCollector.
If non-empty, each of the collected metrics is prefixed by the
provided string and an underscore ("_").
PidFn returns the PID of the process the collector collects metrics
for. It is called upon each collection. By default, the PID of the
current process is used, as determined on construction time by
calling os.Getpid().
If true, any error encountered during collection is reported as an
invalid metric (see NewInvalidMetric). Otherwise, errors are ignored
and the collected metrics will be incomplete. (Possibly, no metrics
will be collected at all.) While that's usually not desired, it is
appropriate for the common "mix-in" of process metrics, where process
metrics are nice to have, but failing to collect them should not
disrupt the collection of the remaining metrics.
func NewProcessCollector(opts ProcessCollectorOpts) Collector
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 than the Registry type
directly). In that way, they are free to use custom Registerer implementation
(e.g. for testing purposes).
MustRegister works like Register but registers any number of
Collectors and panics upon the first registration that causes an
error.
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.
A Collector whose Describe method does not yield any Desc is treated
as unchecked. Registration will always succeed. No check for
re-registering (see previous paragraph) is performed. Thus, the
caller is responsible for not double-registering the same unchecked
Collector, and for providing a Collector that will not cause
inconsistent metrics on collection. (This would lead to scrape
errors.)
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 an unchecked
Collector cannot be unregistered (as its Describe method does not
yield any descriptor).
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.
*Registry
*wrappingRegisterer
func WrapRegistererWith(labels Labels, reg Registerer) Registerer
func WrapRegistererWithPrefix(prefix string, reg Registerer) Registerer
func WrapRegistererWith(labels Labels, reg Registerer) Registerer
func WrapRegistererWithPrefix(prefix string, reg Registerer) Registerer
func github.com/prometheus/client_golang/prometheus/promhttp.InstrumentMetricHandler(reg Registerer, handler http.Handler) http.Handler
var DefaultRegisterer
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. However, the default behavior will change in the
upcoming v1.0.0 of the library. There will be no rank estimations at all by
default. For a sane transition, it is recommended to set the desired rank
estimations explicitly.
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.
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
(unless the Collector is unchecked, see above). 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.
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).
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.
Sending no descriptor at all marks the Collector as “unchecked”,
i.e. no checks will be performed at registration time, and the
Collector may yield any Metric it sees fit in its Collect method.
This method idempotently sends the same descriptors throughout the
lifetime of the Collector. It may be called concurrently and
therefore must be implemented in a concurrency safe way.
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.
Observe adds a single observation to the histogram.
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. Callers of Write should
still make sure of sorting if they depend on it.
Histogram(interface)
*histogram
*noObjectivesSummary
*summary
T : Collector
T : CounterFunc
T : GaugeFunc
T : Histogram
T : Metric
T : Observer
T : UntypedFunc
func NewSummary(opts SummaryOpts) Summary
func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary
SummaryOpts bundles the options for creating a Summary metric. It is
mandatory to set Name to a non-empty string. While all other fields are
optional and can safely be left at their zero value, it is recommended to set
a help string and to explicitly set the Objectives field to the desired value
as the default value will change in the upcoming v1.0.0 of the library.
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.
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").
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.
Due to the way a Summary is represented in the Prometheus text format
and how it is handled by the Prometheus server internally, “quantile”
is an illegal label name. Construction of a Summary or SummaryVec
will panic if this label name is used in ConstLabels.
ConstLabels are only used rarely. In particular, do not use them to
attach the same labels to all your metrics. Those use cases are
better covered by target labels set by the scraping Prometheus
server, or by one specific metric (e.g. a build_info or a
machine_role metric). See also
https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels
Help provides information about this Summary.
Metrics with the same fully-qualified name must have the same Help
string.
MaxAge defines the duration for which an observation stays relevant
for the summary. Must be positive. The default value is DefMaxAge.
Namestring
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.
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 an empty map, resulting in a summary without
quantiles.
Subsystemstring
func NewSummary(opts SummaryOpts) Summary
func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec
func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary
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.
metricVec*metricVecmetricVec.curry[]curriedLabelValue
hashAdd and hashAddByte can be replaced for testing collision handling.
metricVec.hashAddBytefunc(h uint64, b byte) uint64metricVec.metricMap*metricMapmetricVec.metricMap.desc*DescmetricVec.metricMap.metricsmap[uint64][]metricWithLabelValues
// Protects metrics.
metricVec.metricMap.newMetricfunc(labelValues ...string) Metric
Collect implements Collector.
CurryWith returns a vector curried with the provided labels, i.e. the
returned vector has those labels pre-set for all labeled operations performed
on it. The cardinality of the curried vector is reduced accordingly. The
order of the remaining labels stays the same (just with the curried labels
taken out of the sequence – which is relevant for the
(GetMetric)WithLabelValues methods). It is possible to curry a curried
vector, but only with labels not yet used for currying before.
The metrics contained in the SummaryVec are shared between the curried and
uncurried vectors. They are just accessed differently. Curried and uncurried
vectors behave identically in terms of collection. Only one must be
registered with a given registry (usually the uncurried version). The Reset
method deletes all metrics, even if called on a curried vector.
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 Desc. 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.
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.
Describe implements Collector. It will send exactly one Desc to the provided
channel.
GetMetricWith returns the Summary 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 Summary is created. Implications of
creating a Summary without using it and keeping the Summary 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 (minus any curried labels).
This method is used for the same purpose as
GetMetricWithLabelValues(...string). See there for pros and cons of the two
methods.
GetMetricWithLabelValues returns the Summary 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 Summary is created.
It is possible to call this method without using the returned Summary to only
create the new Summary but leave it at its starting value, a Summary without
any observations.
Keeping the Summary 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 Summary from the SummaryVec. In that case,
the Summary will still exist, but it will not be exported anymore, even if a
Summary 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 (minus any curried labels).
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.
MustCurryWith works as CurryWith but panics where CurryWith would have
returned an error.
Reset deletes all metrics in this vector.
With works as GetMetricWith, but panics where GetMetricWithLabels would have
returned an error. Not returning an error allows shortcuts like
myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Observe(42.21)
WithLabelValues works as GetMetricWithLabelValues, but panics where
GetMetricWithLabelValues would have returned an error. Not returning an
error allows shortcuts like
myVec.WithLabelValues("404", "GET").Observe(42.21)
( T) curryWith(labels Labels) (*metricVec, error)
deleteByHashWithLabelValues removes the metric from the hash bucket h. If
there are multiple matches in the bucket, use lvs to select a metric and
remove only that metric.
deleteByHashWithLabels removes the metric from the hash bucket h. If there
are multiple matches in the bucket, use lvs to select a metric and remove
only that metric.
( T) getMetricWith(labels Labels) (Metric, error)
getMetricWithHashAndLabelValues gets a metric while handling possible
collisions in the hash space. Must be called while holding the read mutex.
getMetricWithHashAndLabels gets a metric while handling possible collisions in
the hash space. Must be called while holding read mutex.
( T) getMetricWithLabelValues(lvs ...string) (Metric, error)
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
( T) hashLabelValues(vals []string) (uint64, error)( T) hashLabels(labels Labels) (uint64, error)
T : Collector
*T : ObserverVec
func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec
Timer is a helper type to time functions. Use NewTimer to create new
instances.
begintime.TimeobserverObserver
ObserveDuration records the duration passed since the Timer was created with
NewTimer. It calls the Observe method of the Observer provided during
construction with the duration in seconds as an argument. The observed
duration is also returned. ObserveDuration is usually called with a defer
statement.
Note that this method is only guaranteed to never observe negative durations
if used with Go1.9+.
func NewTimer(o Observer) *Timer
UntypedFunc works like GaugeFunc but the collected metric is of type
"Untyped". UntypedFunc is useful to mirror an external metric of unknown
type.
To create UntypedFunc instances, use NewUntypedFunc.
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
(unless the Collector is unchecked, see above). 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.
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).
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.
Sending no descriptor at all marks the Collector as “unchecked”,
i.e. no checks will be performed at registration time, and the
Collector may yield any Metric it sees fit in its Collect method.
This method idempotently sends the same descriptors throughout the
lifetime of the Collector. It may be called concurrently and
therefore must be implemented in a concurrency safe way.
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.
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. Callers of Write should
still make sure of sorting if they depend on it.
Counter(interface)CounterFunc(interface)Gauge(interface)GaugeFunc(interface)Histogram(interface)Summary(interface)
*counter
*gauge
*histogram
*noObjectivesSummary
*summary
*valueFunc
T : Collector
T : CounterFunc
T : GaugeFunc
T : Metric
func NewUntypedFunc(opts UntypedOpts, function func() float64) UntypedFunc
UntypedOpts is an alias for Opts. See there for doc comments.
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.
ConstLabels are only used rarely. In particular, do not use them to
attach the same labels to all your metrics. Those use cases are
better covered by target labels set by the scraping Prometheus
server, or by one specific metric (e.g. a build_info or a
machine_role metric). See also
https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels
Help provides information about this metric.
Metrics with the same fully-qualified name must have the same Help
string.
Namestring
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.
Subsystemstring
func NewUntypedFunc(opts UntypedOpts, function func() float64) UntypedFunc
desc*DesclabelPairs[]*dto.LabelPairselfCollectorselfCollectorselfCollector.selfMetric
valBits contains the bits of the represented float64 value, while
valInt stores values that are exact integers. Both have to go first
in the struct to guarantee alignment for atomic operations.
http://golang.org/pkg/sync/atomic/#pkg-note-BUG
valIntuint64(*T) Add(v float64)
Collect implements Collector.
(*T) Desc() *Desc
Describe implements Collector.
(*T) Inc()(*T) Write(out *dto.Metric) error
init provides the selfCollector with a reference to the metric it is supposed
to collect. It is usually called within the factory function to create a
metric. See example.
*T : Collector
*T : Counter
*T : CounterFunc
*T : GaugeFunc
*T : Metric
*T : UntypedFunc
countAndHotIdx enables lock-free writes with use of atomic updates.
The most significant bit is the hot index [0 or 1] of the count field
below. Observe calls update the hot one. All remaining bits count the
number of Observe calls. Observe starts by incrementing this counter,
and finish by incrementing the count field in the respective
histogramCounts, as a marker for completion.
Calls of the Write method (which are non-mutating reads from the
perspective of the histogram) swap the hot–cold under the writeMtx
lock. A cooldown is awaited (while locked) by comparing the number of
observations with the initiation count. Once they match, then the
last observation on the now cool one has completed. All cool fields must
be merged into the new hot before releasing writeMtx.
Fields with atomic access first! See alignment constraint:
http://golang.org/pkg/sync/atomic/#pkg-note-BUG
Two counts, one is "hot" for lock-free observations, the other is
"cold" for writing out a dto.Metric. It has to be an array of
pointers to guarantee 64bit alignment of the histogramCounts, see
http://golang.org/pkg/sync/atomic/#pkg-note-BUG.
desc*DesclabelPairs[]*dto.LabelPairselfCollectorselfCollectorselfCollector.selfMetricupperBounds[]float64
// Only used in the Write method.
Collect implements Collector.
(*T) Desc() *Desc
Describe implements Collector.
(*T) Observe(v float64)(*T) Write(out *dto.Metric) error
init provides the selfCollector with a reference to the metric it is supposed
to collect. It is usually called within the factory function to create a
metric. See example.
*T : Collector
*T : CounterFunc
*T : GaugeFunc
*T : Histogram
*T : Metric
*T : Observer
*T : Summary
*T : UntypedFunc
buckets[]uint64countuint64
sumBits contains the bits of the float64 representing the sum of all
observations. sumBits and count have to go first in the struct to
guarantee alignment for atomic operations.
http://golang.org/pkg/sync/atomic/#pkg-note-BUG
labelPairSorter implements sort.Interface. It is used to sort a slice of
dto.LabelPair pointers.
( T) Len() int( T) Less(i, j int) bool( T) Swap(i, j int)
T : sort.Interface
T : github.com/aws/aws-sdk-go/aws/corehandlers.lener
memStatsMetrics provide description, value, and value type for memstat metrics.
metricMap is a helper for metricVec and shared between differently curried
metricVecs.
desc*Descmetricsmap[uint64][]metricWithLabelValues
// Protects metrics.
newMetricfunc(labelValues ...string) Metric
Collect implements Collector.
Describe implements Collector. It will send exactly one Desc to the provided
channel.
Reset deletes all metrics in this vector.
deleteByHashWithLabelValues removes the metric from the hash bucket h. If
there are multiple matches in the bucket, use lvs to select a metric and
remove only that metric.
deleteByHashWithLabels removes the metric from the hash bucket h. If there
are multiple matches in the bucket, use lvs to select a metric and remove
only that metric.
getMetricWithHashAndLabelValues gets a metric while handling possible
collisions in the hash space. Must be called while holding the read mutex.
getMetricWithHashAndLabels gets a metric while handling possible collisions in
the hash space. Must be called while holding read mutex.
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
*T : Collector
metricVec is a Collector to bundle metrics of the same name that differ in
their label values. metricVec is not used directly (and therefore
unexported). It is used as a building block for implementations of vectors of
a given metric type, like GaugeVec, CounterVec, SummaryVec, and HistogramVec.
It also handles label currying.
curry[]curriedLabelValue
hashAdd and hashAddByte can be replaced for testing collision handling.
hashAddBytefunc(h uint64, b byte) uint64metricMap*metricMapmetricMap.desc*DescmetricMap.metricsmap[uint64][]metricWithLabelValues
// Protects metrics.
metricMap.newMetricfunc(labelValues ...string) Metric
Collect implements Collector.
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 Desc. 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.
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.
Describe implements Collector. It will send exactly one Desc to the provided
channel.
Reset deletes all metrics in this vector.
(*T) curryWith(labels Labels) (*metricVec, error)
deleteByHashWithLabelValues removes the metric from the hash bucket h. If
there are multiple matches in the bucket, use lvs to select a metric and
remove only that metric.
deleteByHashWithLabels removes the metric from the hash bucket h. If there
are multiple matches in the bucket, use lvs to select a metric and remove
only that metric.
(*T) getMetricWith(labels Labels) (Metric, error)
getMetricWithHashAndLabelValues gets a metric while handling possible
collisions in the hash space. Must be called while holding the read mutex.
getMetricWithHashAndLabels gets a metric while handling possible collisions in
the hash space. Must be called while holding read mutex.
(*T) getMetricWithLabelValues(lvs ...string) (Metric, error)
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
or creates it and returns the new one.
This function holds the mutex.
(*T) hashLabelValues(vals []string) (uint64, error)(*T) hashLabels(labels Labels) (uint64, error)
T : Collector
func newMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *metricVec
Fields with atomic access first! See alignment constraint:
http://golang.org/pkg/sync/atomic/#pkg-note-BUG
Two counts, one is "hot" for lock-free observations, the other is
"cold" for writing out a dto.Metric. It has to be an array of
pointers to guarantee 64bit alignment of the histogramCounts, see
http://golang.org/pkg/sync/atomic/#pkg-note-BUG.
desc*DesclabelPairs[]*dto.LabelPairselfCollectorselfCollectorselfCollector.selfMetric
// Only used in the Write method.
Collect implements Collector.
(*T) Desc() *Desc
Describe implements Collector.
(*T) Observe(v float64)(*T) Write(out *dto.Metric) error
init provides the selfCollector with a reference to the metric it is supposed
to collect. It is usually called within the factory function to create a
metric. See example.
*T : Collector
*T : CounterFunc
*T : GaugeFunc
*T : Histogram
*T : Metric
*T : Observer
*T : Summary
*T : UntypedFunc
selfCollector implements Collector for a single Metric so that the Metric
collects itself. Add it as an anonymous field to a struct that implements
Metric, and call init with the Metric itself as an argument.
selfMetric
Collect implements Collector.
Describe implements Collector.
init provides the selfCollector with a reference to the metric it is supposed
to collect. It is usually called within the factory function to create a
metric. See example.
*T : Collector
countuint64
sumBits contains the bits of the float64 representing the sum of all
observations. sumBits and count have to go first in the struct to
guarantee alignment for atomic operations.
http://golang.org/pkg/sync/atomic/#pkg-note-BUG
MetricMetricttime.Time
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).
( T) Write(pb *dto.Metric) error
T : Metric
valueFunc is a generic metric for simple values retrieved on collect time
from a function. It implements Metric and Collector. Its effective type is
determined by ValueType. This is a low-level building block used by the
library to back the implementations of CounterFunc, GaugeFunc, and
UntypedFunc.
desc*Descfunctionfunc() float64labelPairs[]*dto.LabelPairselfCollectorselfCollectorselfCollector.selfMetricvalTypeValueType
Collect implements Collector.
(*T) Desc() *Desc
Describe implements Collector.
(*T) Write(out *dto.Metric) error
init provides the selfCollector with a reference to the metric it is supposed
to collect. It is usually called within the factory function to create a
metric. See example.
*T : Collector
*T : CounterFunc
*T : GaugeFunc
*T : Metric
*T : UntypedFunc
func newValueFunc(desc *Desc, valueType ValueType, function func() float64) *valueFunc
Package-Level Functions (total 66, in which 38 are exported)
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.
DescribeByCollect is a helper to implement the Describe method of a custom
Collector. It collects the metrics from the provided Collector and sends
their descriptors to the provided channel.
If a Collector collects the same metrics throughout its lifetime, its
Describe method can simply be implemented as:
func (c customCollector) Describe(ch chan<- *Desc) {
DescribeByCollect(c, ch)
}
However, this will not work if the metrics collected change dynamically over
the lifetime of the Collector in a way that their combined set of descriptors
changes as well. The shortcut implementation will then violate the contract
of the Describe method. If a Collector sometimes collects no metrics at all
(for example vectors like CounterVec, GaugeVec, etc., which only collect
metrics after a metric with a fully specified label set has been accessed),
it might even get registered as an unchecked Collector (cf. the Register
method of the Registerer interface). Hence, only use this shortcut
implementation of Describe if you are certain to fulfill the contract.
The Collector example demonstrates a use of DescribeByCollect.
ExponentialBuckets creates 'count' buckets, where the lowest bucket has an
upper bound of 'start' and each following bucket's upper bound is 'factor'
times the previous bucket's upper bound. The final +Inf bucket is not counted
and not included in the returned slice. The returned slice is meant to be
used for the Buckets field of HistogramOpts.
The function panics if 'count' is 0 or negative, if 'start' is 0 or negative,
or if 'factor' is less than or equal 1.
LinearBuckets creates 'count' buckets, each 'width' wide, where the lowest
bucket has an upper bound of 'start'. The final +Inf bucket is not counted
and not included in the returned slice. The returned slice is meant to be
used for the Buckets field of HistogramOpts.
The function panics if 'count' is zero or negative.
MustNewConstHistogram is a version of NewConstHistogram that panics where
NewConstMetric would have returned an error.
MustNewConstMetric is a version of NewConstMetric that panics where
NewConstMetric would have returned an error.
MustNewConstSummary is a version of NewConstSummary that panics where
NewConstMetric would have returned an error.
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.
NewBuildInfoCollector returns a collector collecting a single metric
"go_build_info" with the constant value 1 and three labels "path", "version",
and "checksum". Their label values contain the main module path, version, and
checksum, respectively. The labels will only have meaningful values if the
binary is built with Go module support and from source code retrieved from
the source repository (rather than the local file system). This is usually
accomplished by building from outside of GOPATH, specifying the full address
of the main package, e.g. "GO111MODULE=on go run
github.com/prometheus/client_golang/examples/random". If built without Go
module support, all label values will be "unknown". If built with Go module
support but using the source code from the local file system, the "path" will
be set appropriately, but "checksum" will be empty and "version" will be
"(devel)".
This collector uses only the build information for the main module. See
https://github.com/povilasv/prommod for an example of a collector for the
module dependencies.
NewConstHistogram returns a metric representing a Prometheus histogram with
fixed values for the count, sum, and bucket counts. As those parameters
cannot be changed, the returned value does not implement the Histogram
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.
buckets is a map of upper bounds to cumulative counts, excluding the +Inf
bucket.
NewConstHistogram returns an error if the length of labelValues is not
consistent with the variable labels in Desc or if Desc is invalid.
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 or if Desc is
invalid.
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 or if Desc is invalid.
NewCounter creates a new Counter based on the provided CounterOpts.
The returned implementation tracks the counter value in two separate
variables, a float64 and a uint64. The latter is used to track calls of the
Inc method and calls of the Add method with a value that can be represented
as a uint64. This allows atomic increments of the counter with optimal
performance. (It is common to have an Inc call in very hot execution paths.)
Both internal tracking values are added up in the Write method. This has to
be taken into account when it comes to precision and overflow behavior.
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.
NewCounterVec creates a new CounterVec based on the provided CounterOpts and
partitioned by the given label names.
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 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 Collector example for a usage pattern.
NewExpvarCollector returns a newly allocated expvar Collector that still has
to be registered with a Prometheus registry.
An expvar Collector collects metrics from the expvar interface. It provides a
quick way to expose numeric values that are already exported via expvar as
Prometheus metrics. Note that the data models of expvar and Prometheus are
fundamentally different, and that the expvar Collector is inherently slower
than native Prometheus metrics. Thus, the expvar Collector is probably great
for experiments and prototying, but you should seriously consider a more
direct implementation of Prometheus metrics for monitoring production
systems.
The exports map has the following meaning:
The keys in the map correspond to expvar keys, i.e. for every expvar key you
want to export as Prometheus metric, you need an entry in the exports
map. The descriptor mapped to each key describes how to export the expvar
value. It defines the name and the help string of the Prometheus metric
proxying the expvar value. The type will always be Untyped.
For descriptors without variable labels, the expvar value must be a number or
a bool. The number is then directly exported as the Prometheus sample
value. (For a bool, 'false' translates to 0 and 'true' to 1). Expvar values
that are not numbers or bools are silently ignored.
If the descriptor has one variable label, the expvar value must be an expvar
map. The keys in the expvar map become the various values of the one
Prometheus label. The values in the expvar map must be numbers or bools again
as above.
For descriptors with more than one variable label, the expvar must be a
nested expvar map, i.e. where the values of the topmost map are maps again
etc. until a depth is reached that corresponds to the number of labels. The
leaves of that structure must be numbers or bools as above to serve as the
sample values.
Anything that does not fit into the scheme above is silently ignored.
NewGauge creates a new Gauge based on the provided GaugeOpts.
The returned implementation is optimized for a fast Set method. If you have a
choice for managing the value of a Gauge via Set vs. Inc/Dec/Add/Sub, pick
the former. For example, the Inc method of the returned Gauge is slower than
the Inc method of a Counter returned by NewCounter. This matches the typical
scenarios for Gauges and Counters, where the former tends to be Set-heavy and
the latter Inc-heavy.
NewGaugeFunc creates a new GaugeFunc based on the provided GaugeOpts. The
value reported is determined by calling the given function from within the
Write method. Take into account that metric collection may happen
concurrently. Therefore, it must be safe to call the provided function
concurrently.
NewGaugeFunc is a good way to create an “info” style metric with a constant
value of 1. Example:
https://github.com/prometheus/common/blob/8558a5b7db3c84fa38b4766966059a7bd5bfa2ee/version/info.go#L36-L56
NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and
partitioned by the given label names.
NewGoCollector returns a collector that exports metrics about the current Go
process. This includes memory stats. To collect those, runtime.ReadMemStats
is called. This requires to “stop the world”, which usually only happens for
garbage collection (GC). Take the following implications into account when
deciding whether to use the Go collector:
1. The performance impact of stopping the world is the more relevant the more
frequently metrics are collected. However, with Go1.9 or later the
stop-the-world time per metrics collection is very short (~25µs) so that the
performance impact will only matter in rare cases. However, with older Go
versions, the stop-the-world duration depends on the heap size and can be
quite significant (~1.7 ms/GiB as per
https://go-review.googlesource.com/c/go/+/34937).
2. During an ongoing GC, nothing else can stop the world. Therefore, if the
metrics collection happens to coincide with GC, it will only complete after
GC has finished. Usually, GC is fast enough to not cause problems. However,
with a very large heap, GC might take multiple seconds, which is enough to
cause scrape timeouts in common setups. To avoid this problem, the Go
collector will use the memstats from a previous collection if
runtime.ReadMemStats takes more than 1s. However, if there are no previously
collected memstats, or their collection is more than 5m ago, the collection
will block until runtime.ReadMemStats succeeds. (The problem might be solved
in Go1.13, see https://github.com/golang/go/issues/19812 for the related Go
issue.)
NewHistogram creates a new Histogram based on the provided HistogramOpts. It
panics if the buckets in HistogramOpts are not in strictly increasing order.
NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and
partitioned by the given label names.
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.
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.
NewMetricWithTimestamp returns a new Metric wrapping the provided Metric in a
way that it has an explicit timestamp set to the provided Time. This is only
useful in rare cases as the timestamp of a Prometheus metric should usually
be set by the Prometheus server during scraping. Exceptions include mirroring
metrics with given timestamps from other metric
sources.
NewMetricWithTimestamp works best with MustNewConstMetric,
MustNewConstHistogram, and MustNewConstSummary, see example.
Currently, the exposition formats used by Prometheus are limited to
millisecond resolution. Thus, the provided time will be rounded down to the
next full millisecond value.
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. Unchecked Collectors (those whose
Describe method does not yield any descriptors) are excluded from the check.
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.
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. The detailed behavior is defined by the provided
ProcessCollectorOpts. The zero value of ProcessCollectorOpts creates a
collector for the current process with an empty namespace string and no error
reporting.
The collector only works on operating systems with a Linux-style proc
filesystem and on Microsoft Windows. On other operating systems, it will not
collect any metrics.
NewRegistry creates a new vanilla Registry without any Collectors
pre-registered.
NewSummary creates a new Summary based on the provided SummaryOpts.
NewSummaryVec creates a new SummaryVec based on the provided SummaryOpts and
partitioned by the given label names.
Due to the way a Summary is represented in the Prometheus text format and how
it is handled by the Prometheus server internally, “quantile” is an illegal
label name. NewSummaryVec will panic if this label name is used.
NewTimer creates a new Timer. The provided Observer is used to observe a
duration in seconds. Timer is usually used to time a function call in the
following way:
func TimeMe() {
timer := NewTimer(myHistogram)
defer timer.ObserveDuration()
// Do actual work.
}
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.
Register registers the provided Collector with the DefaultRegisterer.
Register is a shortcut for DefaultRegisterer.Register(c). See there for more
details.
Unregister removes the registration of the provided Collector from the
DefaultRegisterer.
Unregister is a shortcut for DefaultRegisterer.Unregister(c). See there for
more details.
WrapRegistererWith returns a Registerer wrapping the provided
Registerer. Collectors registered with the returned Registerer will be
registered with the wrapped Registerer in a modified way. The modified
Collector adds the provided Labels to all Metrics it collects (as
ConstLabels). The Metrics collected by the unmodified Collector must not
duplicate any of those labels.
WrapRegistererWith provides a way to add fixed labels to a subset of
Collectors. It should not be used to add fixed labels to all metrics exposed.
Conflicts between Collectors registered through the original Registerer with
Collectors registered through the wrapping Registerer will still be
detected. Any AlreadyRegisteredError returned by the Register method of
either Registerer will contain the ExistingCollector in the form it was
provided to the respective registry.
The Collector example demonstrates a use of WrapRegistererWith.
WrapRegistererWithPrefix returns a Registerer wrapping the provided
Registerer. Collectors registered with the returned Registerer will be
registered with the wrapped Registerer in a modified way. The modified
Collector adds the provided prefix to the name of all Metrics it collects.
WrapRegistererWithPrefix is useful to have one place to prefix all metrics of
a sub-system. To make this work, register metrics of the sub-system with the
wrapping Registerer returned by WrapRegistererWithPrefix. It is rarely useful
to use the same prefix for all metrics exposed. In particular, do not prefix
metric names that are standardized across applications, as that would break
horizontal monitoring, for example the metrics provided by the Go collector
(see NewGoCollector) and the process collector (see NewProcessCollector). (In
fact, those metrics are already prefixed with “go_” or “process_”,
respectively.)
Conflicts between Collectors registered through the original Registerer with
Collectors registered through the wrapping Registerer will still be
detected. Any AlreadyRegisteredError returned by the Register method of
either Registerer will contain the ExistingCollector in the form it was
provided to the respective registry.
WriteToTextfile calls Gather on the provided Gatherer, encodes the result in the
Prometheus text format, and writes it to a temporary file. Upon success, the
temporary file is renamed to the provided filename.
This is intended for use with the textfile collector of the node exporter.
Note that the node exporter expects the filename to be suffixed with ".prom".
checkMetricConsistency checks if the provided Metric is consistent with the
provided MetricFamily. It also hashes the Metric labels and the MetricFamily
name. If the resulting hash is already in the provided metricHashes, an error
is returned. If not, it is added to metricHashes.
checkSuffixCollisions checks for collisions with the “magic” suffixes the
Prometheus text format and the internal metric representation of the
Prometheus server add while flattening Summaries and Histograms.
newValueFunc returns a newly allocated valueFunc with the given Desc and
ValueType. 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 valueFunc is directly registered with Prometheus, the
provided function must be concurrency-safe.
Package-Level Variables (total 8, in which 3 are exported)
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 (currently on Linux only, see NewProcessCollector)
and a Go collector (see NewGoCollector, in particular the note about
stop-the-world implication with Go versions older than 1.9) 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 functions and act on custom instances instead.
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 (currently on Linux only, see NewProcessCollector)
and a Go collector (see NewGoCollector, in particular the note about
stop-the-world implication with Go versions older than 1.9) 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 functions and act on custom instances instead.
DefBuckets are the default Histogram buckets. The default buckets are
tailored to broadly measure the response time (in seconds) of a network
service. Most likely, however, you will be required to define buckets
customized to your use case.
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 (currently on Linux only, see NewProcessCollector)
and a Go collector (see NewGoCollector, in particular the note about
stop-the-world implication with Go versions older than 1.9) 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 functions and act on custom instances instead.
DefBuckets are the default Histogram buckets. The default buckets are
tailored to broadly measure the response time (in seconds) of a network
service. Most likely, however, you will be required to define buckets
customized to your use case.
quantileLabel is used for the label that defines the quantile in a
summary.
reservedLabelPrefix is a prefix which is not legal in user-supplied
label names.
The pages are generated with Goldsv0.3.2-preview. (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.