metrics

package
v0.0.0-...-d8b0a59 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Gin Metrics Library

This directory contains a reusable Prometheus metrics package extracted from the patterns used in Traefik's metrics implementation and adapted for Gin services.

What it provides

  • Prometheus registry and /metrics handler.
  • Gin middleware for HTTP request count, latency, request bytes, and response bytes.
  • Optional request header labels on *_http_requests_total.
  • Backend request, retry, and health metrics.
  • Runtime registration of new Prometheus metrics in the same registry.
  • Stale series cleanup for routes, listeners, services, and backend URLs after topology changes.

Quick start

package main

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	appmetrics "github.com/traefik/traefik/v3/metrics"
)

func main() {
	registry := appmetrics.New(appmetrics.Config{
		Prefix:       "orders",
		Buckets:      []float64{0.05, 0.1, 0.3, 1, 3},
		HeaderLabels: map[string]string{"tenant": "X-Tenant"},
	})

	router := gin.New()
	router.Use(registry.GinMiddleware(appmetrics.GinMiddlewareOptions{
		ShouldObserve: func(c *gin.Context) bool {
			return c.FullPath() != "/metrics"
		},
	}))

	router.GET("/metrics", registry.GinHandler())
	router.GET("/orders/:id", func(c *gin.Context) {
		start := time.Now()

		c.JSON(http.StatusOK, gin.H{"id": c.Param("id")})

		registry.ObserveBackendRequest(appmetrics.BackendRequestObservation{
			Service:    "inventory",
			Method:     http.MethodGet,
			Protocol:   "http",
			StatusCode: http.StatusOK,
			Duration:   time.Since(start),
		})
	})

	registry.SyncGinRoutes(router)
	registry.UpdateResources(appmetrics.ResourceSnapshot{
		Services: []string{"inventory"},
		BackendURLs: map[string][]string{
			"inventory": {"http://inventory.default.svc.cluster.local"},
		},
	})

	cacheHits := registry.NewCounterVec(prometheus.CounterOpts{
		Name: "cache_hits_total",
		Help: "Cache hit count.",
	}, []string{"cache"})
	cacheHits.WithLabelValues("product").Inc()

	_ = router.Run(":8080")
}

Metric names

With Prefix: "orders", the main metrics are:

  • orders_http_requests_total
  • orders_http_request_duration_seconds
  • orders_http_requests_bytes_total
  • orders_http_responses_bytes_total
  • orders_backend_requests_total
  • orders_backend_request_duration_seconds
  • orders_backend_retries_total
  • orders_backend_server_up

Resource cleanup

If routes or backend targets change at runtime, call UpdateResources again with the latest snapshot. Stale time series are removed after the next Prometheus scrape, which matches the cleanup strategy used in Traefik.

Add custom metrics at runtime

You can register extra Prometheus collectors after New(...) returns:

jobsTotal := registry.NewCounterVec(prometheus.CounterOpts{
	Name: "jobs_total",
	Help: "Background jobs processed.",
}, []string{"queue", "result"})

jobsTotal.WithLabelValues("email", "success").Inc()

You can also create non-Vec metrics when you do not need dynamic labels:

totalJobs := registry.NewCounter(prometheus.CounterOpts{
	Name: "jobs_total",
	Help: "Background jobs processed.",
})

totalJobs.Add(1)

If you need fixed labels on a non-Vec metric, use ConstLabels in prometheus.CounterOpts, GaugeOpts, HistogramOpts, or SummaryOpts.

If you already created a collector yourself, register it into the same registry:

inFlight := prometheus.NewGaugeVec(prometheus.GaugeOpts{
	Name: registry.MetricName("workers_inflight"),
	Help: "In-flight workers.",
}, []string{"worker"})

registry.MustRegisterCollectors(inFlight)

If a runtime metric should be cleaned automatically when routes, listeners, services, or backend URLs disappear, register it with resource label mappings:

workerLatency := registry.NewManagedHistogramVec(prometheus.HistogramOpts{
	Name: "worker_latency_seconds",
	Help: "Background worker latency.",
}, []string{"service_name", "backend_url"}, appmetrics.ResourceLabelNames{
	Service:    "service_name",
	BackendURL: "backend_url",
})

workerLatency.WithLabelValues("inventory", "http://inventory.default.svc.cluster.local").Observe(0.12)

UpdateResources(...) will then remove stale time series for this metric after the next scrape, using the label names you mapped.

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

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

func New(config Config) *Registry

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

func (r *Registry) AddBackendRetry(service string, delta float64)

AddBackendRetry increments the backend retry counter for the given service.

func (*Registry) AddOpenConnections

func (r *Registry) AddOpenConnections(listener, protocol string, delta float64)

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

func (r *Registry) Handler() http.Handler

Handler returns a standard net/http Prometheus handler backed by this registry's isolated collector set.

func (*Registry) MarkConfigReload

func (r *Registry) MarkConfigReload(success bool)

MarkConfigReload records a configuration reload attempt and whether the last attempt succeeded.

func (*Registry) MetricName

func (r *Registry) MetricName(name string) string

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

func (r *Registry) SetBackendServerUp(service, url string, up bool)

SetBackendServerUp updates the health gauge for one backend target.

func (*Registry) SetOpenConnections

func (r *Registry) SetOpenConnections(listener, protocol string, value float64)

SetOpenConnections sets the open-connections gauge for a listener and protocol to an absolute value.

func (*Registry) SetTLSCertNotAfter

func (r *Registry) SetTLSCertNotAfter(cn, serial, sans string, notAfter time.Time)

SetTLSCertNotAfter records the expiration timestamp of a TLS certificate.

func (*Registry) SyncGinRoutes

func (r *Registry) SyncGinRoutes(engine *gin.Engine)

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.

Jump to

Keyboard shortcuts

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