Documentation
¶
Overview ¶
Package metrics provides a reusable Prometheus metrics registry for Gin-based HTTP services.
It keeps the parts of Traefik's Prometheus implementation that are broadly useful in application code: request counters, latency histograms, backend health metrics, optional header labels, and stale-series cleanup when routes or backend targets disappear.
Index ¶
- type BackendRequestObservation
- type Config
- type GinMiddlewareOptions
- type Registry
- func (r *Registry) AddBackendRetry(service string, delta float64)
- func (r *Registry) AddOpenConnections(listener, protocol string, delta float64)
- func (r *Registry) GinHandler() gin.HandlerFunc
- func (r *Registry) GinMiddleware(options GinMiddlewareOptions) gin.HandlerFunc
- func (r *Registry) Handler() http.Handler
- func (r *Registry) MarkConfigReload(success bool)
- func (r *Registry) MetricName(name string) string
- func (r *Registry) MustRegisterCollectors(collectors ...prometheus.Collector)
- func (r *Registry) MustRegisterManagedCollector(collector prometheus.Collector, resourceLabels ResourceLabelNames)
- func (r *Registry) NewCounter(opts prometheus.CounterOpts) prometheus.Counter
- func (r *Registry) NewCounterVec(opts prometheus.CounterOpts, labelNames []string) *prometheus.CounterVec
- func (r *Registry) NewGauge(opts prometheus.GaugeOpts) prometheus.Gauge
- func (r *Registry) NewGaugeVec(opts prometheus.GaugeOpts, labelNames []string) *prometheus.GaugeVec
- func (r *Registry) NewHistogram(opts prometheus.HistogramOpts) prometheus.Histogram
- func (r *Registry) NewHistogramVec(opts prometheus.HistogramOpts, labelNames []string) *prometheus.HistogramVec
- func (r *Registry) NewManagedCounterVec(opts prometheus.CounterOpts, labelNames []string, ...) *prometheus.CounterVec
- func (r *Registry) NewManagedGaugeVec(opts prometheus.GaugeOpts, labelNames []string, ...) *prometheus.GaugeVec
- func (r *Registry) NewManagedHistogramVec(opts prometheus.HistogramOpts, labelNames []string, ...) *prometheus.HistogramVec
- func (r *Registry) NewManagedSummaryVec(opts prometheus.SummaryOpts, labelNames []string, ...) *prometheus.SummaryVec
- func (r *Registry) NewSummary(opts prometheus.SummaryOpts) prometheus.Summary
- func (r *Registry) NewSummaryVec(opts prometheus.SummaryOpts, labelNames []string) *prometheus.SummaryVec
- func (r *Registry) ObserveBackendRequest(observation BackendRequestObservation)
- func (r *Registry) ObserveServerRequest(observation ServerRequestObservation)
- func (r *Registry) PrometheusRegistry() *prometheus.Registry
- func (r *Registry) RegisterCollector(collector prometheus.Collector) error
- func (r *Registry) RegisterManagedCollector(collector prometheus.Collector, resourceLabels ResourceLabelNames) error
- func (r *Registry) SetBackendServerUp(service, url string, up bool)
- func (r *Registry) SetOpenConnections(listener, protocol string, value float64)
- func (r *Registry) SetTLSCertNotAfter(cn, serial, sans string, notAfter time.Time)
- func (r *Registry) SyncGinRoutes(engine *gin.Engine)
- func (r *Registry) UpdateResources(snapshot ResourceSnapshot)
- type ResourceLabelNames
- type ResourceSnapshot
- type ServerRequestObservation
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BackendRequestObservation ¶
type BackendRequestObservation struct {
// Service is the logical backend service name.
Service string
// Method is the outbound HTTP method.
Method string
// Protocol is an application-level protocol label, typically http or https.
Protocol string
// StatusCode is the backend response status code.
StatusCode int
// Duration is the backend request latency.
Duration time.Duration
// RequestBytes is the number of bytes sent to the backend.
RequestBytes int64
// ResponseBytes is the number of bytes received from the backend.
ResponseBytes int64
// TLSVersion is an optional TLS version label for TLS-only counters.
TLSVersion string
// TLSCipher is an optional TLS cipher label for TLS-only counters.
TLSCipher string
}
BackendRequestObservation describes one outbound request to a backend service that should be recorded in the built-in backend metrics.
type Config ¶
type Config struct {
// Prefix is prepended to every metric name created by this package.
// For example, Prefix "orders" turns "http_requests_total" into
// "orders_http_requests_total".
Prefix string
// Buckets configures the default histogram buckets for latency-style metrics.
// It is applied to the built-in histograms and to custom histograms when the
// caller does not explicitly provide buckets.
Buckets []float64
// HeaderLabels maps exported metric label names to HTTP request header names.
// The mapping is only applied to built-in HTTP request counters.
HeaderLabels map[string]string
// RegisterProcessMetrics enables the standard Prometheus process collector in
// the registry created by New.
RegisterProcessMetrics bool
// RegisterGoMetrics enables the standard Prometheus Go runtime collector in
// the registry created by New.
RegisterGoMetrics bool
// RegisterServerMetrics enables the standard Prometheus server collector in
// the registry created by New.
RegisterServerMetrics bool
}
Config controls how the reusable metrics registry is initialized.
The same Config is used for both the built-in HTTP/backend metrics and any custom Prometheus collectors created through Registry helper methods.
type GinMiddlewareOptions ¶
type GinMiddlewareOptions struct {
// RouteLabel overrides the default route label resolution. When nil, the Gin
// full path is used and falls back to "unmatched".
RouteLabel func(*gin.Context) string
// ProtocolLabel overrides the default protocol label resolution. When nil,
// requests are labeled as https when TLS is present and http otherwise.
ProtocolLabel func(*gin.Context) string
// ShouldObserve decides whether the current request should be recorded. It is
// commonly used to exclude the /metrics endpoint from self-observation.
ShouldObserve func(*gin.Context) bool
}
GinMiddlewareOptions customizes how Gin requests are turned into metric label values.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is the reusable Prometheus-backed metrics facade exposed by this package.
It owns one isolated Prometheus registry, the built-in Gin-oriented metrics, helper constructors for runtime metrics, and the topology-aware cleanup state used by UpdateResources.
func New ¶
New creates a standalone Registry with built-in HTTP/server/backend metrics.
The returned Registry is ready to expose /metrics, record Gin traffic, accept runtime custom collectors, and clean stale series when UpdateResources is called with the latest topology snapshot.
func (*Registry) AddBackendRetry ¶
AddBackendRetry increments the backend retry counter for the given service.
func (*Registry) AddOpenConnections ¶
AddOpenConnections adjusts the open-connections gauge for a listener and protocol by delta.
func (*Registry) GinHandler ¶
func (r *Registry) GinHandler() gin.HandlerFunc
GinHandler adapts Handler into a Gin handler function and aborts the Gin chain after serving the metrics response.
func (*Registry) GinMiddleware ¶
func (r *Registry) GinMiddleware(options GinMiddlewareOptions) gin.HandlerFunc
GinMiddleware records built-in HTTP request metrics for Gin handlers.
It captures request count, latency, request bytes, response bytes, and optional TLS labels. The middleware is intentionally generic so callers can decide how routes and protocols should be labeled.
func (*Registry) Handler ¶
Handler returns a standard net/http Prometheus handler backed by this registry's isolated collector set.
func (*Registry) MarkConfigReload ¶
MarkConfigReload records a configuration reload attempt and whether the last attempt succeeded.
func (*Registry) MetricName ¶
MetricName returns the fully prefixed metric name used by this registry. It is useful when callers create collectors manually and still want naming to remain consistent with the registry prefix.
func (*Registry) MustRegisterCollectors ¶
func (r *Registry) MustRegisterCollectors(collectors ...prometheus.Collector)
MustRegisterCollectors is the panic-on-error form of RegisterCollector.
func (*Registry) MustRegisterManagedCollector ¶
func (r *Registry) MustRegisterManagedCollector(collector prometheus.Collector, resourceLabels ResourceLabelNames)
MustRegisterManagedCollector is the panic-on-error form of RegisterManagedCollector.
func (*Registry) NewCounter ¶
func (r *Registry) NewCounter(opts prometheus.CounterOpts) prometheus.Counter
NewCounter creates, prefixes, registers, and returns a plain Prometheus counter.
Use this helper when the metric does not need dynamic labels. For fixed labels, rely on opts.ConstLabels.
func (*Registry) NewCounterVec ¶
func (r *Registry) NewCounterVec(opts prometheus.CounterOpts, labelNames []string) *prometheus.CounterVec
NewCounterVec creates, prefixes, registers, and returns a Prometheus CounterVec.
func (*Registry) NewGauge ¶
func (r *Registry) NewGauge(opts prometheus.GaugeOpts) prometheus.Gauge
NewGauge creates, prefixes, registers, and returns a plain Prometheus gauge.
func (*Registry) NewGaugeVec ¶
func (r *Registry) NewGaugeVec(opts prometheus.GaugeOpts, labelNames []string) *prometheus.GaugeVec
NewGaugeVec creates, prefixes, registers, and returns a Prometheus GaugeVec.
func (*Registry) NewHistogram ¶
func (r *Registry) NewHistogram(opts prometheus.HistogramOpts) prometheus.Histogram
NewHistogram creates, prefixes, registers, and returns a plain Prometheus histogram.
When opts.Buckets is empty, the registry-level default buckets are used.
func (*Registry) NewHistogramVec ¶
func (r *Registry) NewHistogramVec(opts prometheus.HistogramOpts, labelNames []string) *prometheus.HistogramVec
NewHistogramVec creates, prefixes, registers, and returns a Prometheus HistogramVec. Empty bucket definitions inherit the registry defaults.
func (*Registry) NewManagedCounterVec ¶
func (r *Registry) NewManagedCounterVec(opts prometheus.CounterOpts, labelNames []string, resourceLabels ResourceLabelNames) *prometheus.CounterVec
NewManagedCounterVec creates a CounterVec that also participates in UpdateResources-based stale-series cleanup.
func (*Registry) NewManagedGaugeVec ¶
func (r *Registry) NewManagedGaugeVec(opts prometheus.GaugeOpts, labelNames []string, resourceLabels ResourceLabelNames) *prometheus.GaugeVec
NewManagedGaugeVec creates a GaugeVec that also participates in UpdateResources-based stale-series cleanup.
func (*Registry) NewManagedHistogramVec ¶
func (r *Registry) NewManagedHistogramVec(opts prometheus.HistogramOpts, labelNames []string, resourceLabels ResourceLabelNames) *prometheus.HistogramVec
NewManagedHistogramVec creates a HistogramVec that also participates in UpdateResources-based stale-series cleanup.
func (*Registry) NewManagedSummaryVec ¶
func (r *Registry) NewManagedSummaryVec(opts prometheus.SummaryOpts, labelNames []string, resourceLabels ResourceLabelNames) *prometheus.SummaryVec
NewManagedSummaryVec creates a SummaryVec that also participates in UpdateResources-based stale-series cleanup.
func (*Registry) NewSummary ¶
func (r *Registry) NewSummary(opts prometheus.SummaryOpts) prometheus.Summary
NewSummary creates, prefixes, registers, and returns a plain Prometheus summary.
func (*Registry) NewSummaryVec ¶
func (r *Registry) NewSummaryVec(opts prometheus.SummaryOpts, labelNames []string) *prometheus.SummaryVec
NewSummaryVec creates, prefixes, registers, and returns a Prometheus SummaryVec.
func (*Registry) ObserveBackendRequest ¶
func (r *Registry) ObserveBackendRequest(observation BackendRequestObservation)
ObserveBackendRequest records one outbound request into the built-in backend-facing metrics.
func (*Registry) ObserveServerRequest ¶
func (r *Registry) ObserveServerRequest(observation ServerRequestObservation)
ObserveServerRequest records one inbound request into the built-in server-facing metrics.
func (*Registry) PrometheusRegistry ¶
func (r *Registry) PrometheusRegistry() *prometheus.Registry
PrometheusRegistry exposes the underlying Prometheus registry for advanced integrations, tests, and manual gather operations.
func (*Registry) RegisterCollector ¶
func (r *Registry) RegisterCollector(collector prometheus.Collector) error
RegisterCollector registers an arbitrary Prometheus collector in the current registry.
If the collector supports DeletePartialMatch, it is routed through the registry's internal cleanup-aware collector state so that it participates in scrape ordering consistently with built-in metrics. Otherwise it is registered directly in the underlying Prometheus registry.
func (*Registry) RegisterManagedCollector ¶
func (r *Registry) RegisterManagedCollector(collector prometheus.Collector, resourceLabels ResourceLabelNames) error
RegisterManagedCollector registers a custom collector that should also participate in resource-based stale-series cleanup.
Only vector-style collectors that implement DeletePartialMatch can be managed, because cleanup must be able to remove individual label combinations.
func (*Registry) SetBackendServerUp ¶
SetBackendServerUp updates the health gauge for one backend target.
func (*Registry) SetOpenConnections ¶
SetOpenConnections sets the open-connections gauge for a listener and protocol to an absolute value.
func (*Registry) SetTLSCertNotAfter ¶
SetTLSCertNotAfter records the expiration timestamp of a TLS certificate.
func (*Registry) SyncGinRoutes ¶
SyncGinRoutes snapshots the currently registered Gin routes into the cleanup topology so route-scoped metrics can be deleted when routes disappear.
func (*Registry) UpdateResources ¶
func (r *Registry) UpdateResources(snapshot ResourceSnapshot)
UpdateResources publishes the latest active topology to the cleanup engine.
Time series for removed resources are not deleted immediately. They remain visible for the next scrape and are then removed, matching the same scrape- safe cleanup strategy used by Traefik.
type ResourceLabelNames ¶
type ResourceLabelNames struct {
// Listener names the label that holds a listener identifier.
Listener string
// Route names the label that holds a route identifier.
Route string
// Service names the label that holds a logical backend service identifier.
Service string
// BackendURL names the label that holds a concrete backend target URL.
// This requires Service to be set as well so cleanup can scope URL removal to
// a specific service.
BackendURL string
}
ResourceLabelNames tells the registry which labels of a managed custom metric correspond to topology resources tracked by UpdateResources.
When a managed custom metric is registered, the cleanup logic uses these label names to remove stale time series after routes, listeners, services, or backend URLs disappear from the latest ResourceSnapshot.
type ResourceSnapshot ¶
type ResourceSnapshot struct {
// Listeners contains the active inbound listener names, such as entrypoint
// names or logical server ports.
Listeners []string
// Routes contains the active route identifiers. For Gin integrations this is
// typically the registered route pattern, such as "/users/:id".
Routes []string
// Services contains the active logical backend service names.
Services []string
// BackendURLs contains the active backend target URLs keyed by service name.
// A service may exist with an empty backend URL list when the service itself
// is still valid but currently has no concrete upstream target.
BackendURLs map[string][]string
}
ResourceSnapshot describes the currently active topology known to the application.
UpdateResources compares the latest snapshot with the previous one and marks metrics tied to removed listeners, routes, services, or backend URLs for deletion after the next Prometheus scrape.
type ServerRequestObservation ¶
type ServerRequestObservation struct {
// Headers is used to resolve configured HeaderLabels.
Headers http.Header
// Route is the logical route identifier, usually the Gin full path.
Route string
// Method is the HTTP method, such as GET or POST.
Method string
// Protocol is an application-level protocol label, typically http or https.
Protocol string
// StatusCode is the final HTTP response status code.
StatusCode int
// Duration is the total request handling latency.
Duration time.Duration
// RequestBytes is the inbound request size in bytes.
RequestBytes int64
// ResponseBytes is the outbound response size in bytes.
ResponseBytes int64
// TLSVersion is an optional TLS version label for TLS-only counters.
TLSVersion string
// TLSCipher is an optional TLS cipher label for TLS-only counters.
TLSCipher string
}
ServerRequestObservation describes one inbound HTTP request that should be recorded in the built-in server-side metrics.