promhttp

package
v1.12.2 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2022 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package promhttp provides tooling around HTTP servers and clients.

First, the package allows the creation of http.Handler instances to expose Prometheus metrics via HTTP. promhttp.Handler acts on the prometheus.DefaultGatherer. With HandlerFor, you can create a handler for a custom registry or anything that implements the Gatherer interface. It also allows the creation of handlers that act differently on errors or allow to log errors.

Second, the package provides tooling to instrument instances of http.Handler via middleware. Middleware wrappers follow the naming scheme InstrumentHandlerX, where X describes the intended use of the middleware. See each function's doc comment for specific details.

Finally, the package allows for an http.RoundTripper to be instrumented via middleware. Middleware wrappers follow the naming scheme InstrumentRoundTripperX, where X describes the intended use of the middleware. See each function's doc comment for specific details.

Index

Constants

View Source
const (
	TextVersion        = "0.0.4"
	ProtoType          = `application/vnd.google.protobuf`
	ProtoProtocol      = `io.prometheus.client.MetricFamily`
	ProtoFmt           = ProtoType + "; proto=" + ProtoProtocol + ";"
	OpenMetricsType    = `application/openmetrics-text`
	OpenMetricsVersion = "0.0.1"

	// The Content-Type values for the different wire protocols.
	FmtUnknown      Format = `<unknown>`
	FmtText         Format = `text/plain; version=` + TextVersion + `; charset=utf-8`
	FmtProtoDelim   Format = ProtoFmt + ` encoding=delimited`
	FmtProtoText    Format = ProtoFmt + ` encoding=text`
	FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text`
	FmtOpenMetrics  Format = OpenMetricsType + `; version=` + OpenMetricsVersion + `; charset=utf-8`
)

Variables

This section is empty.

Functions

func FinalizeOpenMetrics added in v1.12.2

func FinalizeOpenMetrics(w io.Writer) (written int, err error)

FinalizeOpenMetrics writes the final `# EOF\n` line required by OpenMetrics.

func Handler

func Handler() http.Handler

Handler returns an http.Handler for the prometheus.DefaultGatherer, using default HandlerOpts, i.e. it reports the first error as an HTTP error, it has no error logging, and it applies compression if requested by the client.

The returned http.Handler is already instrumented using the InstrumentMetricHandler function and the prometheus.DefaultRegisterer. If you create multiple http.Handlers by separate calls of the Handler function, the metrics used for instrumentation will be shared between them, providing global scrape counts.

This function is meant to cover the bulk of basic use cases. If you are doing anything that requires more customization (including using a non-default Gatherer, different instrumentation, and non-default HandlerOpts), use the HandlerFor function. See there for details.

func HandlerFor

func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler

HandlerFor returns an uninstrumented http.Handler for the provided Gatherer. The behavior of the Handler is defined by the provided HandlerOpts. Thus, HandlerFor is useful to create http.Handlers for custom Gatherers, with non-default HandlerOpts, and/or with custom (or no) instrumentation. Use the InstrumentMetricHandler function to apply the same kind of instrumentation as it is used by the Handler function.

func InstrumentHandlerCounter added in v0.9.0

func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler) http.HandlerFunc

InstrumentHandlerCounter is a middleware that wraps the provided http.Handler to observe the request result with the provided CounterVec. The CounterVec must have valid metric and label names and must have zero, one, or two non-const non-curried labels. For those, the only allowed label names are "code" and "method". The function panics otherwise. Partitioning of the CounterVec happens by HTTP status code and/or HTTP method if the respective instance label names are present in the CounterVec. For unpartitioned counting, use a CounterVec with zero labels.

If the wrapped Handler does not set a status code, a status code of 200 is assumed.

If the wrapped Handler panics, the Counter is not incremented.

See the example for InstrumentHandlerDuration for example usage.

func InstrumentHandlerDuration added in v0.9.0

func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc

InstrumentHandlerDuration is a middleware that wraps the provided http.Handler to observe the request duration with the provided ObserverVec. The ObserverVec must have valid metric and label names and must have zero, one, or two non-const non-curried labels. For those, the only allowed label names are "code" and "method". The function panics otherwise. The Observe method of the Observer in the ObserverVec is called with the request duration in seconds. Partitioning happens by HTTP status code and/or HTTP method if the respective instance label names are present in the ObserverVec. For unpartitioned observations, use an ObserverVec with zero labels. Note that partitioning of Histograms is expensive and should be used judiciously.

If the wrapped Handler does not set a status code, a status code of 200 is assumed.

If the wrapped Handler panics, no values are reported.

Note that this method is only guaranteed to never observe negative durations if used with Go1.9+.

func InstrumentHandlerInFlight added in v0.9.0

func InstrumentHandlerInFlight(g prometheus.Gauge, next http.Handler) http.Handler

InstrumentHandlerInFlight is a middleware that wraps the provided http.Handler. It sets the provided prometheus.Gauge to the number of requests currently handled by the wrapped http.Handler.

See the example for InstrumentHandlerDuration for example usage.

func InstrumentHandlerRequestSize added in v0.9.0

func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc

InstrumentHandlerRequestSize is a middleware that wraps the provided http.Handler to observe the request size with the provided ObserverVec. The ObserverVec must have valid metric and label names and must have zero, one, or two non-const non-curried labels. For those, the only allowed label names are "code" and "method". The function panics otherwise. The Observe method of the Observer in the ObserverVec is called with the request size in bytes. Partitioning happens by HTTP status code and/or HTTP method if the respective instance label names are present in the ObserverVec. For unpartitioned observations, use an ObserverVec with zero labels. Note that partitioning of Histograms is expensive and should be used judiciously.

If the wrapped Handler does not set a status code, a status code of 200 is assumed.

If the wrapped Handler panics, no values are reported.

See the example for InstrumentHandlerDuration for example usage.

func InstrumentHandlerResponseSize added in v0.9.0

func InstrumentHandlerResponseSize(obs prometheus.ObserverVec, next http.Handler) http.Handler

InstrumentHandlerResponseSize is a middleware that wraps the provided http.Handler to observe the response size with the provided ObserverVec. The ObserverVec must have valid metric and label names and must have zero, one, or two non-const non-curried labels. For those, the only allowed label names are "code" and "method". The function panics otherwise. The Observe method of the Observer in the ObserverVec is called with the response size in bytes. Partitioning happens by HTTP status code and/or HTTP method if the respective instance label names are present in the ObserverVec. For unpartitioned observations, use an ObserverVec with zero labels. Note that partitioning of Histograms is expensive and should be used judiciously.

If the wrapped Handler does not set a status code, a status code of 200 is assumed.

If the wrapped Handler panics, no values are reported.

See the example for InstrumentHandlerDuration for example usage.

func InstrumentHandlerTimeToWriteHeader added in v0.9.0

func InstrumentHandlerTimeToWriteHeader(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc

InstrumentHandlerTimeToWriteHeader is a middleware that wraps the provided http.Handler to observe with the provided ObserverVec the request duration until the response headers are written. The ObserverVec must have valid metric and label names and must have zero, one, or two non-const non-curried labels. For those, the only allowed label names are "code" and "method". The function panics otherwise. The Observe method of the Observer in the ObserverVec is called with the request duration in seconds. Partitioning happens by HTTP status code and/or HTTP method if the respective instance label names are present in the ObserverVec. For unpartitioned observations, use an ObserverVec with zero labels. Note that partitioning of Histograms is expensive and should be used judiciously.

If the wrapped Handler panics before calling WriteHeader, no value is reported.

Note that this method is only guaranteed to never observe negative durations if used with Go1.9+.

See the example for InstrumentHandlerDuration for example usage.

func InstrumentMetricHandler added in v0.9.0

func InstrumentMetricHandler(reg prometheus.Registerer, handler http.Handler) http.Handler

InstrumentMetricHandler is usually used with an http.Handler returned by the HandlerFor function. It instruments the provided http.Handler with two metrics: A counter vector "promhttp_metric_handler_requests_total" to count scrapes partitioned by HTTP status code, and a gauge "promhttp_metric_handler_requests_in_flight" to track the number of simultaneous scrapes. This function idempotently registers collectors for both metrics with the provided Registerer. It panics if the registration fails. The provided metrics are useful to see how many scrapes hit the monitored target (which could be from different Prometheus servers or other scrapers), and how often they overlap (which would result in more than one scrape in flight at the same time). Note that the scrapes-in-flight gauge will contain the scrape by which it is exposed, while the scrape counter will only get incremented after the scrape is complete (as only then the status code is known). For tracking scrape durations, use the "scrape_duration_seconds" gauge created by the Prometheus server upon each scrape.

func MetricFamilyToOpenMetrics added in v1.12.2

func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily) (written int, err error)

MetricFamilyToOpenMetrics converts a MetricFamily proto message into the OpenMetrics text format and writes the resulting lines to 'out'. It returns the number of bytes written and any error encountered. The output will have the same order as the input, no further sorting is performed. Furthermore, this function assumes the input is already sanitized and does not perform any sanity checks. If the input contains duplicate metrics or invalid metric or label names, the conversion will result in invalid text format output.

This function fulfills the type 'expfmt.encoder'.

Note that OpenMetrics requires a final `# EOF` line. Since this function acts on individual metric families, it is the responsibility of the caller to append this line to 'out' once all metric families have been written. Conveniently, this can be done by calling FinalizeOpenMetrics.

The output should be fully OpenMetrics compliant. However, there are a few missing features and peculiarities to avoid complications when switching from Prometheus to OpenMetrics or vice versa:

  • Counters are expected to have the `_total` suffix in their metric name. In the output, the suffix will be truncated from the `# TYPE` and `# HELP` line. A counter with a missing `_total` suffix is not an error. However, its type will be set to `unknown` in that case to avoid invalid OpenMetrics output.
  • No support for the following (optional) features: `# UNIT` line, `_created` line, info type, stateset type, gaugehistogram type.
  • The size of exemplar labels is not checked (i.e. it's possible to create exemplars that are larger than allowed by the OpenMetrics specification).
  • The value of Counters is not checked. (OpenMetrics doesn't allow counters with a `NaN` value.)

func MetricFamilyToText added in v1.12.2

func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err error)

MetricFamilyToText converts a MetricFamily proto message into text format and writes the resulting lines to 'out'. It returns the number of bytes written and any error encountered. The output will have the same order as the input, no further sorting is performed. Furthermore, this function assumes the input is already sanitized and does not perform any sanity checks. If the input contains duplicate metrics or invalid metric or label names, the conversion will result in invalid text format output.

This method fulfills the type 'prometheus.encoder'.

Types

type Accept added in v1.12.2

type Accept struct {
	Type, SubType string
	Q             float64
	Params        map[string]string
}

func ParseAccept added in v1.12.2

func ParseAccept(header string) (accept []Accept)

Parse an Accept Header string returning a sorted list of clauses

type Closer added in v1.12.2

type Closer interface {
	Close() error
}

type Encoder added in v1.12.2

type Encoder interface {
	Encode(*dto.MetricFamily) error
}

Encoder types encode metric families into an underlying wire protocol.

func NewEncoder added in v1.12.2

func NewEncoder(w io.Writer, format Format) Encoder

type Format added in v1.12.2

type Format string

Format specifies the HTTP content type of the different wire protocols.

func Negotiate added in v1.12.2

func Negotiate(h http.Header) Format

Negotiate returns the Content-Type based on the given Accept header. If no appropriate accepted type is found, FmtText is returned (which is the Prometheus text format). This function will never negotiate FmtOpenMetrics, as the support is still experimental. To include the option to negotiate FmtOpenMetrics, use NegotiateOpenMetrics.

func NegotiateIncludingOpenMetrics added in v1.12.2

func NegotiateIncludingOpenMetrics(h http.Header) Format

NegotiateIncludingOpenMetrics works like Negotiate but includes FmtOpenMetrics as an option for the result. Note that this function is temporary and will disappear once FmtOpenMetrics is fully supported and as such may be negotiated by the normal Negotiate function.

type HandlerErrorHandling

type HandlerErrorHandling int

HandlerErrorHandling defines how a Handler serving metrics will handle errors.

const (
	// Serve an HTTP status code 500 upon the first error
	// encountered. Report the error message in the body. Note that HTTP
	// errors cannot be served anymore once the beginning of a regular
	// payload has been sent. Thus, in the (unlikely) case that encoding the
	// payload into the negotiated wire format fails, serving the response
	// will simply be aborted. Set an ErrorLog in HandlerOpts to detect
	// those errors.
	HTTPErrorOnError HandlerErrorHandling = iota
	// Ignore errors and try to serve as many metrics as possible.  However,
	// if no metrics can be served, serve an HTTP status code 500 and the
	// last error message in the body. Only use this in deliberate "best
	// effort" metrics collection scenarios. In this case, it is highly
	// recommended to provide other means of detecting errors: By setting an
	// ErrorLog in HandlerOpts, the errors are logged. By providing a
	// Registry in HandlerOpts, the exposed metrics include an error counter
	// "promhttp_metric_handler_errors_total", which can be used for
	// alerts.
	ContinueOnError
	// Panic upon the first error encountered (useful for "crash only" apps).
	PanicOnError
)

These constants cause handlers serving metrics to behave as described if errors are encountered.

type HandlerOpts

type HandlerOpts struct {
	// ErrorLog specifies an optional Logger for errors collecting and
	// serving metrics. If nil, errors are not logged at all. Note that the
	// type of a reported error is often prometheus.MultiError, which
	// formats into a multi-line error string. If you want to avoid the
	// latter, create a Logger implementation that detects a
	// prometheus.MultiError and formats the contained errors into one line.
	ErrorLog Logger
	// ErrorHandling defines how errors are handled. Note that errors are
	// logged regardless of the configured ErrorHandling provided ErrorLog
	// is not nil.
	ErrorHandling HandlerErrorHandling
	// If Registry is not nil, it is used to register a metric
	// "promhttp_metric_handler_errors_total", partitioned by "cause". A
	// failed registration causes a panic. Note that this error counter is
	// different from the instrumentation you get from the various
	// InstrumentHandler... helpers. It counts errors that don't necessarily
	// result in a non-2xx HTTP status code. There are two typical cases:
	// (1) Encoding errors that only happen after streaming of the HTTP body
	// has already started (and the status code 200 has been sent). This
	// should only happen with custom collectors. (2) Collection errors with
	// no effect on the HTTP status code because ErrorHandling is set to
	// ContinueOnError.
	Registry prometheus.Registerer
	// If DisableCompression is true, the handler will never compress the
	// response, even if requested by the client.
	DisableCompression bool
	// The number of concurrent HTTP requests is limited to
	// MaxRequestsInFlight. Additional requests are responded to with 503
	// Service Unavailable and a suitable message in the body. If
	// MaxRequestsInFlight is 0 or negative, no limit is applied.
	MaxRequestsInFlight int
	// If handling a request takes longer than Timeout, it is responded to
	// with 503 ServiceUnavailable and a suitable Message. No timeout is
	// applied if Timeout is 0 or negative. Note that with the current
	// implementation, reaching the timeout simply ends the HTTP requests as
	// described above (and even that only if sending of the body hasn't
	// started yet), while the bulk work of gathering all the metrics keeps
	// running in the background (with the eventual result to be thrown
	// away). Until the implementation is improved, it is recommended to
	// implement a separate timeout in potentially slow Collectors.
	Timeout time.Duration
	// If true, the experimental OpenMetrics encoding is added to the
	// possible options during content negotiation. Note that Prometheus
	// 2.5.0+ will negotiate OpenMetrics as first priority. OpenMetrics is
	// the only way to transmit exemplars. However, the move to OpenMetrics
	// is not completely transparent. Most notably, the values of "quantile"
	// labels of Summaries and "le" labels of Histograms are formatted with
	// a trailing ".0" if they would otherwise look like integer numbers
	// (which changes the identity of the resulting series on the Prometheus
	// server).
	EnableOpenMetrics bool
}

HandlerOpts specifies options how to serve metrics via an http.Handler. The zero value of HandlerOpts is a reasonable default.

type InstrumentTrace added in v0.9.0

type InstrumentTrace struct {
	GotConn              func(float64)
	PutIdleConn          func(float64)
	GotFirstResponseByte func(float64)
	Got100Continue       func(float64)
	DNSStart             func(float64)
	DNSDone              func(float64)
	ConnectStart         func(float64)
	ConnectDone          func(float64)
	TLSHandshakeStart    func(float64)
	TLSHandshakeDone     func(float64)
	WroteHeaders         func(float64)
	Wait100Continue      func(float64)
	WroteRequest         func(float64)
}

InstrumentTrace is used to offer flexibility in instrumenting the available httptrace.ClientTrace hook functions. Each function is passed a float64 representing the time in seconds since the start of the http request. A user may choose to use separately buckets Histograms, or implement custom instance labels on a per function basis.

type Logger

type Logger interface {
	Println(v ...interface{})
}

Logger is the minimal interface HandlerOpts needs for logging. Note that log.Logger from the standard library implements this interface, and it is easy to implement by custom loggers, if they don't do so already anyway.

type RoundTripperFunc added in v0.9.0

type RoundTripperFunc func(req *http.Request) (*http.Response, error)

The RoundTripperFunc type is an adapter to allow the use of ordinary functions as RoundTrippers. If f is a function with the appropriate signature, RountTripperFunc(f) is a RoundTripper that calls f.

func InstrumentRoundTripperCounter added in v0.9.0

func InstrumentRoundTripperCounter(counter *prometheus.CounterVec, next http.RoundTripper) RoundTripperFunc

InstrumentRoundTripperCounter is a middleware that wraps the provided http.RoundTripper to observe the request result with the provided CounterVec. The CounterVec must have zero, one, or two non-const non-curried labels. For those, the only allowed label names are "code" and "method". The function panics otherwise. Partitioning of the CounterVec happens by HTTP status code and/or HTTP method if the respective instance label names are present in the CounterVec. For unpartitioned counting, use a CounterVec with zero labels.

If the wrapped RoundTripper panics or returns a non-nil error, the Counter is not incremented.

See the example for ExampleInstrumentRoundTripperDuration for example usage.

func InstrumentRoundTripperDuration added in v0.9.0

func InstrumentRoundTripperDuration(obs prometheus.ObserverVec, next http.RoundTripper) RoundTripperFunc

InstrumentRoundTripperDuration is a middleware that wraps the provided http.RoundTripper to observe the request duration with the provided ObserverVec. The ObserverVec must have zero, one, or two non-const non-curried labels. For those, the only allowed label names are "code" and "method". The function panics otherwise. The Observe method of the Observer in the ObserverVec is called with the request duration in seconds. Partitioning happens by HTTP status code and/or HTTP method if the respective instance label names are present in the ObserverVec. For unpartitioned observations, use an ObserverVec with zero labels. Note that partitioning of Histograms is expensive and should be used judiciously.

If the wrapped RoundTripper panics or returns a non-nil error, no values are reported.

Note that this method is only guaranteed to never observe negative durations if used with Go1.9+.

func InstrumentRoundTripperInFlight added in v0.9.0

func InstrumentRoundTripperInFlight(gauge prometheus.Gauge, next http.RoundTripper) RoundTripperFunc

InstrumentRoundTripperInFlight is a middleware that wraps the provided http.RoundTripper. It sets the provided prometheus.Gauge to the number of requests currently handled by the wrapped http.RoundTripper.

See the example for ExampleInstrumentRoundTripperDuration for example usage.

func InstrumentRoundTripperTrace added in v0.9.0

func InstrumentRoundTripperTrace(it *InstrumentTrace, next http.RoundTripper) RoundTripperFunc

InstrumentRoundTripperTrace is a middleware that wraps the provided RoundTripper and reports times to hook functions provided in the InstrumentTrace struct. Hook functions that are not present in the provided InstrumentTrace struct are ignored. Times reported to the hook functions are time since the start of the request. Only with Go1.9+, those times are guaranteed to never be negative. (Earlier Go versions are not using a monotonic clock.) Note that partitioning of Histograms is expensive and should be used judiciously.

For hook functions that receive an error as an argument, no observations are made in the event of a non-nil error value.

See the example for ExampleInstrumentRoundTripperDuration for example usage.

func (RoundTripperFunc) RoundTrip added in v0.9.0

func (rt RoundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip implements the RoundTripper interface.

Jump to

Keyboard shortcuts

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