metric

package module
v1.4.7 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2025 License: BSD-3-Clause Imports: 18 Imported by: 0

README

Lux Metrics Library

A comprehensive metrics library for the Lux ecosystem with built-in context propagation support for Prometheus metrics collection.

Features

  • Full Prometheus Compatibility: Works seamlessly with Prometheus client libraries
  • Context Propagation: Pass context.Context through the entire metrics collection pipeline
  • Timeout Support: Respects Prometheus scrape timeouts via X-Prometheus-Scrape-Timeout-Seconds header
  • Request-Scoped Metrics: Filter or customize metrics based on request parameters
  • Backward Compatible: Existing collectors work without modification
  • Clean Abstraction: No Prometheus types leak outside the package
  • Flexible Architecture: Support for multiple gatherers, registries, and custom collectors

Installation

go get github.com/luxfi/metric@latest

Quick Start

Basic Usage
package main

import (
    "net/http"
    metrics "github.com/luxfi/metric"
)

func main() {
    // Create a new metrics instance
    m := metrics.New("myapp")
    
    // Create metrics
    counter := m.NewCounter("requests_total", "Total number of requests")
    gauge := m.NewGauge("temperature_celsius", "Current temperature")
    histogram := m.NewHistogram("request_duration_seconds", "Request duration", 
        []float64{0.1, 0.5, 1, 2, 5})
    
    // Use metrics
    counter.Inc()
    gauge.Set(23.5)
    histogram.Observe(0.234)
    
    // Expose metrics endpoint
    http.Handle("/metrics", metrics.Handler())
    http.ListenAndServe(":8080", nil)
}
Context-Aware Collectors

The library supports context propagation for advanced use cases:

package main

import (
    "context"
    "database/sql"
    "github.com/prometheus/client_golang/prometheus"
    metrics "github.com/luxfi/metric"
)

// Custom collector that respects context cancellation
type DatabaseCollector struct {
    db *sql.DB
}

func (c *DatabaseCollector) Describe(ch chan<- *prometheus.Desc) {
    ch <- prometheus.NewDesc("db_connections", "Number of database connections", nil, nil)
}

func (c *DatabaseCollector) Collect(ch chan<- prometheus.Metric) {
    c.CollectWithContext(context.Background(), ch)
}

func (c *DatabaseCollector) CollectWithContext(ctx context.Context, ch chan<- prometheus.Metric) {
    // Check if context is cancelled
    select {
    case <-ctx.Done():
        return // Stop collection if cancelled
    default:
    }
    
    // Perform expensive operation with context
    var connections float64
    err := c.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM pg_stat_activity").Scan(&connections)
    if err != nil {
        return
    }
    
    ch <- prometheus.MustNewConstMetric(
        prometheus.NewDesc("db_connections", "Number of database connections", nil, nil),
        prometheus.GaugeValue,
        connections,
    )
}

func main() {
    // Create context-aware registry
    reg := metrics.NewContextRegistry()
    
    // Register context-aware collector
    dbCollector := &DatabaseCollector{db: getDB()}
    reg.MustRegister(dbCollector)
    
    // Create handler with timeout support
    handler := metrics.HandlerForContext(reg, metrics.HandlerOpts{
        Timeout: 10 * time.Second,
        ErrorHandling: promhttp.ContinueOnError,
        MaxRequestsInFlight: 5,
    })
    
    http.Handle("/metrics", handler)
    http.ListenAndServe(":8080", nil)
}
Request-Scoped Metrics

Filter metrics based on request parameters:

handler := metrics.HandlerForContext(reg, metrics.HandlerOpts{
    ContextFunc: func(r *http.Request) context.Context {
        ctx := r.Context()
        
        // Pass query parameters to collectors
        if includes := r.URL.Query().Get("include"); includes != "" {
            ctx = context.WithValue(ctx, "metrics.include", includes)
        }
        
        return ctx
    },
})

// In your collector:
func (c *MyCollector) CollectWithContext(ctx context.Context, ch chan<- prometheus.Metric) {
    // Check what metrics to include
    if includes, ok := ctx.Value("metrics.include").(string); ok {
        if !strings.Contains(includes, "expensive") {
            return // Skip expensive metrics
        }
    }
    
    // Collect expensive metrics...
}

API Reference

Core Interfaces
CollectorWithContext
type CollectorWithContext interface {
    prometheus.Collector
    CollectWithContext(ctx context.Context, ch chan<- prometheus.Metric)
}
GathererWithContext
type GathererWithContext interface {
    prometheus.Gatherer
    GatherWithContext(ctx context.Context) ([]*dto.MetricFamily, error)
}
Registry
ContextRegistry

A registry that supports both standard and context-aware collectors:

reg := metrics.NewContextRegistry()

// Register standard collector
reg.MustRegister(prometheus.NewGoCollector())

// Register context-aware collector
reg.MustRegister(myContextCollector)

// Gather with context
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
metrics, err := reg.GatherWithContext(ctx)
HTTP Handler
HandlerForContext

Creates an HTTP handler with full context support:

handler := metrics.HandlerForContext(gatherer, metrics.HandlerOpts{
    Timeout:             10 * time.Second,
    ErrorHandling:       promhttp.ContinueOnError,
    MaxRequestsInFlight: 10,
    EnableOpenMetrics:   true,
    ContextFunc: func(r *http.Request) context.Context {
        // Custom context derivation
        return r.Context()
    },
})
Utilities
CollectorFunc

Adapter for using functions as collectors:

collector := metrics.NewCollectorFunc(
    func(ch chan<- *prometheus.Desc) {
        ch <- prometheus.NewDesc("my_metric", "help", nil, nil)
    },
    func(ctx context.Context, ch chan<- prometheus.Metric) {
        // Collect with context
        select {
        case <-ctx.Done():
            return
        default:
            // Collect metrics...
        }
    },
)
CollectorAdapter

Wraps standard collectors to be context-aware:

standardCollector := prometheus.NewGoCollector()
contextAware := metrics.NewCollectorAdapter(standardCollector)

Advanced Features

Multi-Gatherer Support

Combine metrics from multiple sources with namespace prefixes:

mg := metrics.NewMultiGathererWithContext()

// Register different registries with namespaces
mg.Register("app", appRegistry)
mg.Register("database", dbRegistry)
mg.Register("cache", cacheRegistry)

// All metrics will be prefixed with their namespace
// e.g., app_requests_total, database_connections, cache_hits
Timeout Handling

The library automatically respects Prometheus scrape timeouts:

  1. Reads X-Prometheus-Scrape-Timeout-Seconds header from Prometheus
  2. Applies the timeout to the context
  3. Context-aware collectors can check ctx.Done() to stop early
  4. Returns partial results if timeout occurs
Error Handling

Configure how errors are handled during metric collection:

handler := metrics.HandlerForContext(reg, metrics.HandlerOpts{
    ErrorHandling: promhttp.HTTPErrorOnError,  // Return HTTP error
    // or
    ErrorHandling: promhttp.ContinueOnError,   // Include error metric
    // or  
    ErrorHandling: promhttp.PanicOnError,      // Panic on error
    
    ErrorLog: func(err error) {
        log.Printf("Metrics error: %v", err)
    },
})

Best Practices

  1. Always check context in long-running collectors:

    select {
    case <-ctx.Done():
        return // Stop if cancelled
    default:
        // Continue collection
    }
    
  2. Use context for expensive operations:

    rows, err := db.QueryContext(ctx, query)
    
  3. Set reasonable timeouts:

    HandlerOpts{
        Timeout: 10 * time.Second, // Default timeout
    }
    
  4. Limit concurrent requests:

    HandlerOpts{
        MaxRequestsInFlight: 10, // Prevent overload
    }
    
  5. Log errors for debugging:

    HandlerOpts{
        ErrorLog: log.Printf,
    }
    

Migration Guide

From Standard Prometheus

Existing Prometheus collectors work without modification:

// Before
reg := prometheus.NewRegistry()
reg.MustRegister(collector)
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))

// After - with context support
reg := metrics.NewContextRegistry()
reg.MustRegister(collector) // Same collector works
http.Handle("/metrics", metrics.HandlerFor(reg))
Adding Context Support

To make a collector context-aware:

// Before
func (c *MyCollector) Collect(ch chan<- prometheus.Metric) {
    expensiveOperation()
    ch <- metric
}

// After
func (c *MyCollector) CollectWithContext(ctx context.Context, ch chan<- prometheus.Metric) {
    select {
    case <-ctx.Done():
        return // Respect cancellation
    default:
    }
    
    expensiveOperationWithContext(ctx)
    ch <- metric
}

// Keep the old method for compatibility
func (c *MyCollector) Collect(ch chan<- prometheus.Metric) {
    c.CollectWithContext(context.Background(), ch)
}

Performance Considerations

  • Context-aware collectors run concurrently by default
  • Cancelled contexts stop collection immediately
  • Non-context collectors continue to completion
  • Use MaxRequestsInFlight to limit concurrent scrapes
  • Timeout applies to entire gathering operation

Testing

Run the test suite:

go test ./...

Run benchmarks:

go test -bench=. -benchmem

Contributing

Contributions are welcome! Please ensure:

  1. All tests pass
  2. New features include tests
  3. Documentation is updated
  4. Code follows Go best practices

License

Copyright (C) 2019-2025, Lux Industries Inc. All rights reserved.

See the file LICENSE for licensing terms.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	NewHistogram       = prometheus.NewHistogram
	NewSummary         = prometheus.NewSummary
	NewSummaryVec      = prometheus.NewSummaryVec
	NewRegistry        = prometheus.NewRegistry
	NewDesc            = prometheus.NewDesc
	MustNewConstMetric = prometheus.MustNewConstMetric
	Register           = prometheus.Register
	MustRegister       = prometheus.MustRegister
	Unregister         = prometheus.Unregister
)

Keep these as direct aliases since they don't need wrapping

View Source
var ErrFailedRegistering = errors.New("failed registering metric")
View Source
var NewPrometheusRegistry = NewRegistry

NewPrometheusRegistry is an alias for NewRegistry for backward compatibility

Functions

func AppendNamespace

func AppendNamespace(namespace, name string) string

AppendNamespace appends a namespace to a metric name if needed

func AsCollector

func AsCollector(m interface{}) prometheus.Collector

AsCollector returns a metric as a prometheus.Collector for registration

func HTTPHandler

func HTTPHandler(gatherer prometheus.Gatherer, opts promhttp.HandlerOpts) http.Handler

HTTPHandler creates an HTTP handler for metrics

func Handler

func Handler() http.Handler

Handler creates a standard HTTP handler with context support using default options.

func HandlerFor

func HandlerFor(gatherer prometheus.Gatherer) http.Handler

HandlerFor creates an HTTP handler with context support for the given gatherer.

func HandlerForContext

func HandlerForContext(gatherer GathererWithContext, opts HandlerOpts) http.Handler

HandlerForContext creates an HTTP handler that serves metrics with context support. It respects the X-Prometheus-Scrape-Timeout-Seconds header and propagates context through the gathering process.

func InstrumentMetricHandler

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

InstrumentMetricHandler wraps a metrics handler with standard HTTP instrumentation.

func MustNewPrometheusConstMetric

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

MustNewPrometheusConstMetric creates a new constant metric

func NewContextCollectorWrapper

func NewContextCollectorWrapper(c CollectorWithContext) prometheus.Collector

NewContextCollectorWrapper creates a wrapper for a context-aware collector.

func NewGoCollector

func NewGoCollector() prometheus.Collector

NewGoCollector creates a new Go collector

func NewProcessCollector

func NewProcessCollector(opts ProcessCollectorOpts) prometheus.Collector

NewProcessCollector creates a new process collector

func NewPrometheusDesc

func NewPrometheusDesc(fqName, help string, variableLabels []string, constLabels prometheus.Labels) *prometheus.Desc

NewPrometheusDesc creates a new prometheus descriptor

func SetFactory

func SetFactory(factory Factory)

SetFactory sets the global metrics factory

func ToPrometheusGatherer

func ToPrometheusGatherer(r Registry) prometheus.Gatherer

ToPrometheusGatherer converts our Registry to a prometheus.Gatherer Since Registry is already *prometheus.Registry, just return it

func ToPrometheusRegisterer

func ToPrometheusRegisterer(r Registry) prometheus.Registerer

ToPrometheusRegisterer converts our Registry to a prometheus.Registerer Since Registry is already *prometheus.Registry, just return it

func WithContextFunc

func WithContextFunc(fn func(*http.Request) context.Context) func(*HandlerOpts)

WithContextFunc returns a HandlerOpts option that sets a custom context function.

func WithErrorLog

func WithErrorLog(logger func(error)) func(*HandlerOpts)

WithErrorLog returns a HandlerOpts option that sets the error logger.

func WithMaxRequestsInFlight

func WithMaxRequestsInFlight(max int) func(*HandlerOpts)

WithMaxRequestsInFlight returns a HandlerOpts option that sets the max concurrent requests.

func WithTimeout

func WithTimeout(timeout time.Duration) func(*HandlerOpts)

WithTimeout returns a HandlerOpts option that sets the timeout.

func WrapPrometheusRegistererWith

func WrapPrometheusRegistererWith(labels prometheus.Labels, reg prometheus.Registerer) prometheus.Registerer

WrapPrometheusRegistererWith wraps a prometheus registerer with labels

func WrapPrometheusRegistererWithPrefix

func WrapPrometheusRegistererWithPrefix(prefix string, reg prometheus.Registerer) prometheus.Registerer

WrapPrometheusRegistererWithPrefix wraps a prometheus registerer with a prefix

Types

type Averager

type Averager interface {
	Observe(float64)
}

func NewAverager

func NewAverager(name, desc string, reg Registerer) (Averager, error)

func NewAveragerWithErrs

func NewAveragerWithErrs(name, desc string, reg Registerer, errs *Errs) Averager

func NewNoAverager

func NewNoAverager() Averager

type Client

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

Client for requesting metrics from a remote Lux Node instance

func NewClient

func NewClient(uri string) *Client

NewClient returns a new Metrics API Client

func (*Client) GetMetrics

func (c *Client) GetMetrics(ctx context.Context) (map[string]*dto.MetricFamily, error)

GetMetrics returns the metrics from the connected node. The metrics are returned as a map of metric family name to the metric family.

type Collector

type Collector = prometheus.Collector

Collector is an alias for prometheus.Collector

type CollectorAdapter

type CollectorAdapter struct {
	prometheus.Collector
}

CollectorAdapter wraps a standard prometheus.Collector to implement CollectorWithContext.

func (*CollectorAdapter) CollectWithContext

func (a *CollectorAdapter) CollectWithContext(ctx context.Context, ch chan<- prometheus.Metric)

CollectWithContext implements CollectorWithContext by ignoring the context.

type CollectorFunc

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

CollectorFunc is an adapter to allow the use of ordinary functions as context-aware collectors.

func NewCollectorFunc

func NewCollectorFunc(
	descFunc func(chan<- *prometheus.Desc),
	collectFunc func(context.Context, chan<- prometheus.Metric),
) *CollectorFunc

NewCollectorFunc creates a new CollectorFunc.

func (*CollectorFunc) Collect

func (f *CollectorFunc) Collect(ch chan<- prometheus.Metric)

Collect implements prometheus.Collector.

func (*CollectorFunc) CollectWithContext

func (f *CollectorFunc) CollectWithContext(ctx context.Context, ch chan<- prometheus.Metric)

CollectWithContext implements CollectorWithContext.

func (*CollectorFunc) Describe

func (f *CollectorFunc) Describe(ch chan<- *prometheus.Desc)

Describe implements prometheus.Collector.

type CollectorWithContext

type CollectorWithContext interface {
	prometheus.Collector // Embeds the base interface for compatibility

	// CollectWithContext works like Collect but accepts a context for
	// timeout/cancellation and request-scoped values.
	CollectWithContext(ctx context.Context, ch chan<- prometheus.Metric)
}

CollectorWithContext is a Collector that can consume a Context for timeout/cancellation and request-scoped values.

func NewCollectorAdapter

func NewCollectorAdapter(c prometheus.Collector) CollectorWithContext

NewCollectorAdapter creates a new adapter for a standard collector.

type ContextCollectorWrapper

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

ContextCollectorWrapper wraps a CollectorWithContext to implement prometheus.Collector.

func (*ContextCollectorWrapper) Collect

func (w *ContextCollectorWrapper) Collect(ch chan<- prometheus.Metric)

Collect implements prometheus.Collector.

func (*ContextCollectorWrapper) Describe

func (w *ContextCollectorWrapper) Describe(ch chan<- *prometheus.Desc)

Describe implements prometheus.Collector.

type ContextRegistry

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

ContextRegistry is a registry that supports both standard and context-aware collectors. It implements both prometheus.Gatherer and GathererWithContext interfaces.

func NewContextRegistry

func NewContextRegistry() *ContextRegistry

NewContextRegistry creates a new registry that supports both standard and context-aware collectors.

func NewPedanticContextRegistry

func NewPedanticContextRegistry() *ContextRegistry

NewPedanticContextRegistry creates a new registry with extra validation enabled.

func (*ContextRegistry) Gather

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

Gather implements prometheus.Gatherer for backward compatibility.

func (*ContextRegistry) GatherWithContext

func (r *ContextRegistry) GatherWithContext(ctx context.Context) ([]*dto.MetricFamily, error)

GatherWithContext implements GathererWithContext interface.

func (*ContextRegistry) MustRegister

func (r *ContextRegistry) MustRegister(cs ...prometheus.Collector)

MustRegister registers collectors and panics on error.

func (*ContextRegistry) Register

func (r *ContextRegistry) Register(c prometheus.Collector) error

Register registers a collector (either standard or context-aware).

func (*ContextRegistry) Unregister

func (r *ContextRegistry) Unregister(c prometheus.Collector) bool

Unregister removes a collector from the registry.

type Counter

type Counter interface {
	prometheus.Collector
	// Inc increments the counter by 1
	Inc()
	// Add increments the counter by the given value
	Add(float64)
	// Get returns the current value
	Get() float64
}

Counter is a metric that can only increase

func NewCounter

func NewCounter(opts CounterOpts) Counter

Constructor functions that return wrapped types

func NewCounterWithOpts

func NewCounterWithOpts(opts prometheus.CounterOpts) Counter

NewCounterWithOpts creates a wrapped counter from options

func NewNoopCounter

func NewNoopCounter(name string) Counter

NewNoopCounter creates a new standalone noop counter metric

func WrapPrometheusCounter

func WrapPrometheusCounter(c prometheus.Counter) Counter

WrapPrometheusCounter wraps a prometheus.Counter to implement our Counter interface

type CounterOpts

type CounterOpts = prometheus.CounterOpts

Export prometheus types

type CounterVec

type CounterVec interface {
	prometheus.Collector
	// With returns a counter with the given label values
	With(Labels) Counter
	// WithLabelValues returns a counter with the given label values
	WithLabelValues(labelValues ...string) Counter
}

CounterVec is a vector of counters

func NewCounterVec

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

func NewCounterVecWithOpts

func NewCounterVecWithOpts(opts prometheus.CounterOpts, labelNames []string) CounterVec

NewCounterVecWithOpts creates a wrapped counter vec from options

func WrapPrometheusCounterVec

func WrapPrometheusCounterVec(cv *prometheus.CounterVec) CounterVec

WrapPrometheusCounterVec wraps a prometheus.CounterVec to implement our CounterVec interface

type DTOMetricFamily added in v1.4.7

type DTOMetricFamily = dto.MetricFamily

DTOMetricFamily is an alias for dto.MetricFamily for backward compatibility

type Desc

type Desc = *prometheus.Desc

Desc is an alias for prometheus.Desc

type Errs

type Errs struct{ Err error }

Errs is a simple error accumulator used for collecting multiple errors

func (*Errs) Add

func (errs *Errs) Add(errors ...error)

Add adds one or more errors to the accumulator Only the first non-nil error is kept

func (*Errs) Errored

func (errs *Errs) Errored() bool

Errored returns true if any error has been added

type Factory

type Factory interface {
	// New creates a new metrics instance with the given namespace
	New(namespace string) Metrics
	// NewWithRegistry creates a new metrics instance with a custom registry
	NewWithRegistry(namespace string, registry Registry) Metrics
}

Factory creates new metrics instances

func NewNoOpFactory

func NewNoOpFactory() Factory

NewNoOpFactory creates a factory that produces noop metrics

func NewPrometheusFactory

func NewPrometheusFactory() Factory

NewPrometheusFactory creates a factory that produces prometheus-backed metrics

func NewPrometheusFactoryWithRegistry

func NewPrometheusFactoryWithRegistry(registry *prometheus.Registry) Factory

NewPrometheusFactoryWithRegistry creates a factory with a custom prometheus registry

type Gatherer

type Gatherer = prometheus.Gatherer

Gatherer is an alias for prometheus.Gatherer

type GathererFunc

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

GathererFunc is an adapter to allow the use of ordinary functions as Gatherers.

func (GathererFunc) Gather

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

Gather implements prometheus.Gatherer.

type GathererWithContext

type GathererWithContext interface {
	prometheus.Gatherer // Embeds the base interface for compatibility

	// GatherWithContext works like Gather but accepts a context for
	// timeout/cancellation and request-scoped values.
	GatherWithContext(ctx context.Context) ([]*dto.MetricFamily, error)
}

GathererWithContext is a Gatherer that accepts a context.Context for timeout/cancellation propagation and request-scoped values.

type GathererWithContextFunc

type GathererWithContextFunc func(context.Context) ([]*dto.MetricFamily, error)

GathererWithContextFunc is an adapter to allow the use of ordinary functions as context-aware Gatherers.

func (GathererWithContextFunc) Gather

func (f GathererWithContextFunc) Gather() ([]*dto.MetricFamily, error)

Gather implements prometheus.Gatherer for backward compatibility.

func (GathererWithContextFunc) GatherWithContext

func (f GathererWithContextFunc) GatherWithContext(ctx context.Context) ([]*dto.MetricFamily, error)

GatherWithContext implements GathererWithContext.

type Gatherers

type Gatherers = prometheus.Gatherers

Export prometheus types

type Gauge

type Gauge interface {
	prometheus.Collector
	// Set sets the gauge to the given value
	Set(float64)
	// Inc increments the gauge by 1
	Inc()
	// Dec decrements the gauge by 1
	Dec()
	// Add adds the given value to the gauge
	Add(float64)
	// Sub subtracts the given value from the gauge
	Sub(float64)
	// Get returns the current value
	Get() float64
}

Gauge is a metric that can increase or decrease

func NewGauge

func NewGauge(opts GaugeOpts) Gauge

func NewGaugeWithOpts

func NewGaugeWithOpts(opts prometheus.GaugeOpts) Gauge

NewGaugeWithOpts creates a wrapped gauge from options

func NewNoopGauge

func NewNoopGauge(name string) Gauge

NewNoopGauge creates a new standalone noop gauge metric

func WrapPrometheusGauge

func WrapPrometheusGauge(g prometheus.Gauge) Gauge

WrapPrometheusGauge wraps a prometheus.Gauge to implement our Gauge interface

type GaugeOpts

type GaugeOpts = prometheus.GaugeOpts

Export prometheus types

type GaugeVec

type GaugeVec interface {
	prometheus.Collector
	// With returns a gauge with the given label values
	With(Labels) Gauge
	// WithLabelValues returns a gauge with the given label values
	WithLabelValues(labelValues ...string) Gauge
}

GaugeVec is a vector of gauges

func NewGaugeVec

func NewGaugeVec(opts GaugeOpts, labelNames []string) GaugeVec

func NewGaugeVecWithOpts

func NewGaugeVecWithOpts(opts prometheus.GaugeOpts, labelNames []string) GaugeVec

NewGaugeVecWithOpts creates a wrapped gauge vec from options

func WrapPrometheusGaugeVec

func WrapPrometheusGaugeVec(gv *prometheus.GaugeVec) GaugeVec

WrapPrometheusGaugeVec wraps a prometheus.GaugeVec to implement our GaugeVec interface

type HTTPHandlerOpts

type HTTPHandlerOpts = promhttp.HandlerOpts

HTTPHandlerOpts are options for the HTTP handler

type HandlerOpts

type HandlerOpts struct {
	// ErrorLog specifies an optional logger for errors.
	ErrorLog func(error)

	// ErrorHandling defines how errors are handled.
	ErrorHandling promhttp.HandlerErrorHandling

	// Registry is the gatherer to use for metrics.
	Registry prometheus.Gatherer

	// Timeout is the maximum duration for gathering metrics.
	// If zero, no timeout is applied beyond what's in the request context.
	Timeout time.Duration

	// EnableOpenMetrics enables OpenMetrics format support.
	EnableOpenMetrics bool

	// MaxRequestsInFlight limits the number of concurrent metric requests.
	// If zero, no limit is applied.
	MaxRequestsInFlight int

	// ContextFunc allows customizing how the context is derived from the request.
	ContextFunc func(*http.Request) context.Context
}

HandlerOpts are options for the context-aware HTTP handler.

type Histogram

type Histogram interface {
	prometheus.Collector
	// Observe adds a single observation to the histogram
	Observe(float64)
}

Histogram samples observations and counts them in configurable buckets

func NewNoopHistogram

func NewNoopHistogram(name string) Histogram

NewNoopHistogram creates a new standalone noop histogram metric

type HistogramOpts

type HistogramOpts = prometheus.HistogramOpts

Export prometheus types

type HistogramVec

type HistogramVec interface {
	prometheus.Collector
	// With returns a histogram with the given label values
	With(Labels) Histogram
	// WithLabelValues returns a histogram with the given label values
	WithLabelValues(labelValues ...string) Histogram
}

HistogramVec is a vector of histograms

func NewHistogramVec

func NewHistogramVec(opts HistogramOpts, labelNames []string) HistogramVec

func WrapPrometheusHistogramVec added in v1.4.7

func WrapPrometheusHistogramVec(hv *prometheus.HistogramVec) HistogramVec

WrapPrometheusHistogramVec wraps a prometheus.HistogramVec to implement our HistogramVec interface

type Labels

type Labels map[string]string

Labels represents a set of label key-value pairs

type Metric

type Metric = prometheus.Metric

Metric is an alias for prometheus.Metric

type MetricFamilies

type MetricFamilies = []*dto.MetricFamily

MetricFamilies is a slice of metric families

type MetricFamily

type MetricFamily = dto.MetricFamily

MetricFamily alias for dto.MetricFamily

type Metrics

type Metrics interface {
	// NewCounter creates a new counter
	NewCounter(name, help string) Counter
	// NewCounterVec creates a new counter vector
	NewCounterVec(name, help string, labelNames []string) CounterVec

	// NewGauge creates a new gauge
	NewGauge(name, help string) Gauge
	// NewGaugeVec creates a new gauge vector
	NewGaugeVec(name, help string, labelNames []string) GaugeVec

	// NewHistogram creates a new histogram
	NewHistogram(name, help string, buckets []float64) Histogram
	// NewHistogramVec creates a new histogram vector
	NewHistogramVec(name, help string, labelNames []string, buckets []float64) HistogramVec

	// NewSummary creates a new summary
	NewSummary(name, help string, objectives map[float64]float64) Summary
	// NewSummaryVec creates a new summary vector
	NewSummaryVec(name, help string, labelNames []string, objectives map[float64]float64) SummaryVec

	// Registry returns the underlying registry
	Registry() Registry

	// PrometheusRegistry returns the prometheus registerer for compatibility
	PrometheusRegistry() interface{}
}

Metrics is the main interface for creating metrics

func New

func New(namespace string) Metrics

New creates a new metrics instance with the given namespace

func NewNoOp

func NewNoOp() Metrics

NewNoOp creates a no-op metrics instance without namespace

func NewNoOpMetrics

func NewNoOpMetrics(namespace string) Metrics

NewNoOpMetrics creates a no-op metrics instance for testing

func NewPrometheusMetrics

func NewPrometheusMetrics(namespace string, registry *prometheus.Registry) Metrics

NewPrometheusMetrics creates a new prometheus-backed metrics instance

func NewWithRegistry

func NewWithRegistry(namespace string, registry Registry) Metrics

NewWithRegistry creates a new metrics instance with a custom registry

type MetricsHTTPHandler

type MetricsHTTPHandler interface {
	// ServeHTTP handles an HTTP request
	ServeHTTP(w ResponseWriter, r *Request)
}

MetricsHTTPHandler handles HTTP requests for metrics

type MultiGatherer

type MultiGatherer interface {
	prometheus.Gatherer

	// Register adds the outputs of [gatherer] to the results of future calls to
	// Gather with the provided [namespace] added to the metrics.
	Register(namespace string, gatherer prometheus.Gatherer) error

	// Deregister removes the outputs of a gatherer with [namespace] from the results
	// of future calls to Gather. Returns true if a gatherer with [namespace] was
	// found.
	Deregister(namespace string) bool
}

MultiGatherer extends the Gatherer interface by allowing additional gatherers to be registered and deregistered.

func NewLabelGatherer

func NewLabelGatherer(labelName string) MultiGatherer

NewLabelGatherer returns a new MultiGatherer that adds a label to all metrics

func NewMultiGatherer

func NewMultiGatherer() MultiGatherer

NewMultiGatherer returns a new MultiGatherer that merges metrics by namespace

func NewPrefixGatherer

func NewPrefixGatherer() MultiGatherer

NewPrefixGatherer returns a new MultiGatherer that adds a prefix to all metrics

type MultiGathererWithContext

type MultiGathererWithContext interface {
	GathererWithContext

	// Register adds the outputs of gatherer to the results of future calls to
	// Gather with the provided namespace added to the metrics.
	Register(namespace string, gatherer prometheus.Gatherer) error

	// Deregister removes the outputs of a gatherer with namespace from the results
	// of future calls to Gather.
	Deregister(namespace string) bool
}

MultiGathererWithContext extends MultiGatherer with context support.

func NewMultiGathererWithContext

func NewMultiGathererWithContext() MultiGathererWithContext

NewMultiGathererWithContext creates a new MultiGathererWithContext.

type ProcessCollectorOpts

type ProcessCollectorOpts = collectors.ProcessCollectorOpts

ProcessCollectorOpts are options for the process collector

type PrometheusCollector

type PrometheusCollector = prometheus.Collector

PrometheusCollector is an alias for prometheus.Collector Use this when you need to pass collectors to prometheus-specific code

type PrometheusDesc

type PrometheusDesc = prometheus.Desc

PrometheusDesc is an alias for prometheus.Desc

type PrometheusGatherer

type PrometheusGatherer = prometheus.Gatherer

PrometheusGatherer is an alias for prometheus.Gatherer Use this when you need prometheus gatherer functionality

type PrometheusLabels

type PrometheusLabels = prometheus.Labels

PrometheusLabels is an alias for prometheus.Labels

type PrometheusMetric

type PrometheusMetric = prometheus.Metric

PrometheusMetric is an alias for prometheus.Metric

type PrometheusMetricFamily

type PrometheusMetricFamily = dto.MetricFamily

PrometheusMetricFamily is an alias for dto.MetricFamily

type PrometheusRegisterer

type PrometheusRegisterer = prometheus.Registerer

PrometheusRegisterer is an alias for prometheus.Registerer Use this when you need prometheus registerer functionality

type PrometheusValueType

type PrometheusValueType = prometheus.ValueType

PrometheusValueType is an alias for prometheus.ValueType

Prometheus value types

type Registerer

type Registerer = prometheus.Registerer

Registerer is an alias for prometheus.Registerer

type Registry

type Registry = *prometheus.Registry

Registry is an alias for prometheus.Registry to keep it internal We use prometheus.Registry directly but alias it to avoid external dependencies

func MakeAndRegister

func MakeAndRegister(gatherer MultiGatherer, namespace string) (Registry, error)

MakeAndRegister creates a new registry and registers it with the gatherer Returns our Registry alias which is just *prometheus.Registry

func NewNoOpRegistry

func NewNoOpRegistry() Registry

NewNoOpRegistry creates a no-op registry for testing

func WrapPrometheusRegistry

func WrapPrometheusRegistry(promReg *prometheus.Registry) Registry

WrapPrometheusRegistry wraps a prometheus registry in our Registry interface

type Request

type Request interface {
	// Context returns the request context
	Context() context.Context
	// Method returns the HTTP method
	Method() string
	// URL returns the request URL
	URL() string
}

Request represents an HTTP request

type ResponseWriter

type ResponseWriter interface {
	// Write writes data to the response
	Write([]byte) (int, error)
	// WriteHeader writes the status code
	WriteHeader(int)
	// Header returns the response headers
	Header() map[string][]string
}

ResponseWriter is an interface for writing HTTP responses

type Summary

type Summary interface {
	prometheus.Collector
	// Observe adds a single observation to the summary
	Observe(float64)
}

Summary captures individual observations and provides quantiles

func NewNoopSummary

func NewNoopSummary(name string) Summary

NewNoopSummary creates a new standalone noop summary metric

type SummaryOpts

type SummaryOpts = prometheus.SummaryOpts

Export prometheus types

type SummaryVec

type SummaryVec interface {
	// With returns a summary with the given label values
	With(Labels) Summary
	// WithLabelValues returns a summary with the given label values
	WithLabelValues(labelValues ...string) Summary
}

SummaryVec is a vector of summaries

type TextParser added in v1.4.7

type TextParser = expfmt.TextParser

TextParser is an alias for expfmt.TextParser

type Timer

type Timer interface {
	// Start starts the timer and returns a function to stop it
	Start() func()
	// ObserveTime observes the given duration
	ObserveTime(time.Duration)
}

Timer measures durations

Jump to

Keyboard shortcuts

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