metric

package module
v1.4.11 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2026 License: BSD-3-Clause Imports: 21 Imported by: 0

README

Lux Metrics Library

github.com/luxfi/metric is the native metrics library for Lux. It produces a scrape-compatible text exposition format and is designed for low overhead in hot paths.

Features

  • Single, native API for counters, gauges, histograms, summaries, and vectors
  • Scrape-compatible text format encoder and HTTP handler
  • Registry + gatherer model for composition
  • Optional no-op build for benchmark runs (build-tagged swap)

Installation

go get github.com/luxfi/metric@latest

Quick Start

package main

import (
	"net/http"

	"github.com/luxfi/metric"
)

func main() {
	m := metric.New("myapp")

	requests := m.NewCounter("requests_total", "Total requests")
	latency := m.NewHistogram("request_seconds", "Request latency (s)", metric.DefBuckets)

	requests.Inc()
	latency.Observe(0.123)

	http.Handle("/metrics", metric.Handler())
	_ = http.ListenAndServe(":8080", nil)
}

Custom Registry

reg := metric.NewRegistry()
m := metric.NewWithRegistry("myapp", reg)

requests := m.NewCounter("requests_total", "Total requests")
requests.Inc()

handler := metric.NewHTTPHandler(reg, metric.HandlerOpts{})

Vector Metrics

m := metric.New("myapp")
byRoute := m.NewCounterVec("requests_total", "Requests by route", []string{"method", "route"})

byRoute.WithLabelValues("GET", "/").Inc()

Metrics Off Build

For benchmark runs, you can swap the entire package to no-op implementations using build tags. This keeps call sites unchanged while minimizing overhead.

go test -tags metrics ./...

When built without the metrics tag, metric.NewRegistry() and the package defaults return no-op implementations. Pre-bind label values in hot paths to avoid argument construction overhead.

Documentation

Overview

Package metric provides metrics collection. Designed for minimal allocations and standalone operation.

Index

Constants

View Source
const (
	NamespaceSeparatorByte = '_'
	NamespaceSeparator     = string(NamespaceSeparatorByte)
)

Variables

View Source
var DefBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}

DefBuckets defines default histogram buckets.

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

Functions

func AppendNamespace

func AppendNamespace(namespace, name string) string

AppendNamespace appends a namespace to a metric name if needed

func EncodeText added in v1.4.11

func EncodeText(w io.Writer, families []*MetricFamily) error

EncodeText encodes metric families in the metrics text format.

func HTTPHandler

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

HTTPHandler creates an HTTP handler for metrics (compatibility alias).

func Handler

func Handler() http.Handler

Handler is a convenience method for exposing the default registry.

func HandlerFor

func HandlerFor(gatherer Gatherer) http.Handler

HandlerFor returns an HTTP handler for the provided gatherer.

func HandlerForWithOpts added in v1.4.11

func HandlerForWithOpts(gatherer Gatherer, opts HandlerOpts) http.Handler

HandlerForWithOpts returns an HTTP handler for the provided gatherer and options.

func IsValidLabelName added in v1.4.11

func IsValidLabelName(name string) bool

IsValidLabelName returns true if name is a valid label name.

func IsValidMetricName added in v1.4.11

func IsValidMetricName(name string) bool

IsValidMetricName returns true if name is a valid metric name.

func NativeToDTO added in v1.4.11

func NativeToDTO(families []*MetricFamily) []*dto.MetricFamily

NativeToDTO converts native MetricFamily slice to wire MetricFamily slice. This is used at the RPC boundary when sending metrics over gRPC.

func NewHTTPHandler added in v1.4.11

func NewHTTPHandler(gatherer Gatherer, opts HandlerOpts) http.Handler

NewHTTPHandler creates an HTTP handler for metrics.

func ParseText added in v1.4.11

func ParseText(r io.Reader) (map[string]*MetricFamily, error)

ParseText parses the metrics text format into metric families.

func Push added in v1.4.11

func Push(opts PushOpts) error

Push gathers metrics and pushes them to a remote HTTP endpoint.

func SetFactory

func SetFactory(factory Factory)

SetFactory sets the global metrics factory.

func ValidateGatherer added in v1.4.11

func ValidateGatherer(gatherer Gatherer) error

ValidateGatherer returns a non-nil error if the gatherer is nil.

func ValidateLabelName added in v1.4.11

func ValidateLabelName(name string) error

ValidateLabelName validates a label name against the Prometheus text format rules.

func ValidateLabels added in v1.4.11

func ValidateLabels(labels Labels) error

ValidateLabels validates all label names in the provided map.

func ValidateMetricName added in v1.4.11

func ValidateMetricName(name string) error

ValidateMetricName validates a metric name against the Prometheus text format rules.

func WriteGoMetrics added in v1.4.11

func WriteGoMetrics(w io.Writer) error

WriteGoMetrics writes Go runtime metrics to w in the text format.

func WriteProcessMetrics added in v1.4.11

func WriteProcessMetrics(w io.Writer) error

WriteProcessMetrics writes process metrics to w in the text format.

Types

type APIInterceptor added in v1.4.10

type APIInterceptor interface {
	InterceptRequest(i *rpc.RequestInfo) *http.Request
	AfterRequest(i *rpc.RequestInfo)
}

APIInterceptor tracks request durations and errors for RPC handlers.

func NewAPIInterceptor added in v1.4.10

func NewAPIInterceptor(registry Registry) (APIInterceptor, error)

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 Bucket added in v1.4.11

type Bucket struct {
	UpperBound      float64
	CumulativeCount uint64
}

Bucket represents a histogram bucket.

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]*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 interface{}

Collector is a marker interface for compatibility with Registerer.

func AsCollector

func AsCollector(v interface{}) Collector

AsCollector returns a metric as a Collector for registration. Registration is a no-op for high-perf metrics, so this function simply returns the input value.

func NewGoCollector

func NewGoCollector() Collector

NewGoCollector creates a new Go collector (no-op for now).

func NewProcessCollector

func NewProcessCollector(opts ProcessCollectorOpts) Collector

NewProcessCollector creates a new process collector (no-op for now).

type Counter

type Counter interface {
	Inc()
	Add(float64)
	Get() float64
}

Counter is a metric that can only increase.

func NewCounter

func NewCounter(opts CounterOpts) Counter

NewCounter creates a new counter with the given options.

func NewNoopCounter

func NewNoopCounter() Counter

NewNoopCounter returns a no-op counter.

type CounterOpts

type CounterOpts struct {
	Namespace   string
	Subsystem   string
	Name        string
	Help        string
	ConstLabels Labels
}

CounterOpts configures a counter metric.

type CounterVec

type CounterVec interface {
	With(Labels) Counter
	WithLabelValues(...string) Counter
}

CounterVec is a labeled counter collection.

func NewCounterVec

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

NewCounterVec creates a new counter vector with the given options.

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(namespace string) Metrics
	NewWithRegistry(namespace string, registry Registry) Metrics
}

Factory creates new metrics instances.

func NewFactory added in v1.4.11

func NewFactory() Factory

NewFactory creates a factory that produces metrics.

func NewFactoryWithRegistry added in v1.4.11

func NewFactoryWithRegistry(reg Registry) Factory

NewFactoryWithRegistry creates a factory using an existing registry when possible.

func NewNoOpFactory

func NewNoOpFactory() Factory

NewNoOpFactory returns a factory that produces no-op metrics.

type Gatherer

type Gatherer interface {
	Gather() ([]*MetricFamily, error)
}

Gatherer gathers metric families for exposition.

type Gatherers

type Gatherers []Gatherer

Gatherers is a helper type for slices of gatherers.

type Gauge

type Gauge interface {
	Set(float64)
	Inc()
	Dec()
	Add(float64)
	Sub(float64)
	Get() float64
}

Gauge is a metric that can increase or decrease.

func NewGauge

func NewGauge(opts GaugeOpts) Gauge

NewGauge creates a new gauge with the given options.

func NewNoopGauge

func NewNoopGauge() Gauge

NewNoopGauge returns a no-op gauge.

type GaugeOpts

type GaugeOpts struct {
	Namespace   string
	Subsystem   string
	Name        string
	Help        string
	ConstLabels Labels
}

GaugeOpts configures a gauge metric.

type GaugeVec

type GaugeVec interface {
	With(Labels) Gauge
	WithLabelValues(...string) Gauge
}

GaugeVec is a labeled gauge collection.

func NewGaugeVec

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

NewGaugeVec creates a new gauge vector with the given options.

type HTTPHandlerOpts

type HTTPHandlerOpts = HandlerOpts

HTTPHandlerOpts is an alias for HandlerOpts for compatibility.

type HandlerErrorHandling added in v1.4.11

type HandlerErrorHandling int

HandlerErrorHandling defines behavior on gather errors.

const (
	// HandlerErrorHandlingHTTPError causes the handler to return HTTP 500 on error.
	HandlerErrorHandlingHTTPError HandlerErrorHandling = iota
	// HandlerErrorHandlingContinue writes what it can and logs the error.
	HandlerErrorHandlingContinue
)

type HandlerOpts

type HandlerOpts struct {
	// Timeout overrides the scrape timeout. If zero, the scrape header is used if present.
	Timeout time.Duration
	// ErrorHandling controls how gather errors are handled.
	ErrorHandling HandlerErrorHandling
	// ErrorLog is used when ErrorHandling is Continue.
	ErrorLog interface{ Println(...any) }
}

HandlerOpts configures metrics handlers.

type Histogram

type Histogram interface {
	Observe(float64)
}

Histogram samples observations and counts them in configurable buckets.

func NewHistogram

func NewHistogram(opts HistogramOpts) Histogram

NewHistogram creates a new histogram with the given options.

func NewNoopHistogram

func NewNoopHistogram() Histogram

NewNoopHistogram returns a no-op histogram.

type HistogramOpts

type HistogramOpts struct {
	Namespace   string
	Subsystem   string
	Name        string
	Help        string
	ConstLabels Labels
	Buckets     []float64
}

HistogramOpts configures a histogram metric.

type HistogramVec

type HistogramVec interface {
	With(Labels) Histogram
	WithLabelValues(...string) Histogram
}

HistogramVec is a labeled histogram collection.

func NewHistogramVec

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

NewHistogramVec creates a new histogram vector with the given options.

type LabelPair added in v1.4.11

type LabelPair struct {
	Name  string
	Value string
}

LabelPair is a name-value pair for metric labels.

type Labels

type Labels map[string]string

Labels represents a set of label key-value pairs.

type Metric

type Metric struct {
	Labels []LabelPair
	Value  MetricValue
}

Metric represents a single metric with its labels and value.

type MetricDesc added in v1.4.11

type MetricDesc struct {
	Name string
	Help string
	Type MetricType
}

MetricDesc describes a metric.

type MetricFamilies

type MetricFamilies = []*MetricFamily

MetricFamilies is a slice of metric families.

type MetricFamily

type MetricFamily struct {
	Name    string
	Help    string
	Type    MetricType
	Metrics []Metric
}

MetricFamily is a collection of metrics with the same name and type.

func DTOToNative added in v1.4.11

func DTOToNative(dtoFamilies []*dto.MetricFamily) []*MetricFamily

DTOToNative converts wire MetricFamily slice to native MetricFamily slice. This is used at the RPC boundary when receiving metrics from gRPC.

func GatherGoMetrics added in v1.4.11

func GatherGoMetrics() ([]*MetricFamily, error)

GatherGoMetrics returns metric families describing the Go runtime.

func GatherProcessMetrics added in v1.4.11

func GatherProcessMetrics(opts ProcessCollectorOpts) ([]*MetricFamily, error)

GatherProcessMetrics returns metric families describing the current process.

type MetricType added in v1.4.11

type MetricType int32

MetricType defines the type of a metric.

const (
	MetricTypeCounter MetricType = iota
	MetricTypeGauge
	MetricTypeHistogram
	MetricTypeSummary
	MetricTypeUntyped
)

func (MetricType) String added in v1.4.11

func (t MetricType) String() string

type MetricValue added in v1.4.11

type MetricValue struct {
	// For counter/gauge
	Value float64

	// For histogram
	SampleCount uint64
	SampleSum   float64
	Buckets     []Bucket

	// For summary
	Quantiles []Quantile
}

MetricValue holds the value of a metric.

type Metrics

type Metrics interface {
	NewCounter(name, help string) Counter
	NewCounterVec(name, help string, labelNames []string) CounterVec
	NewGauge(name, help string) Gauge
	NewGaugeVec(name, help string, labelNames []string) GaugeVec
	NewHistogram(name, help string, buckets []float64) Histogram
	NewHistogramVec(name, help string, labelNames []string, buckets []float64) HistogramVec
	NewSummary(name, help string, objectives map[float64]float64) Summary
	NewSummaryVec(name, help string, labelNames []string, objectives map[float64]float64) SummaryVec
	Registry() Registry
}

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 returns a no-op metrics instance without requiring a namespace.

func NewNoOpMetrics

func NewNoOpMetrics(namespace string) Metrics

NewNoOpMetrics returns a no-op metrics instance.

func NewWithRegistry

func NewWithRegistry(namespace string, registry Registry) Metrics

NewWithRegistry creates a new metrics instance with the provided registry.

type MetricsHTTPHandler

type MetricsHTTPHandler interface {
	ServeHTTP(w ResponseWriter, r *Request)
}

MetricsHTTPHandler handles HTTP requests for metrics.

type MultiGatherer

type MultiGatherer interface {
	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 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 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 ProcessCollectorOpts

type ProcessCollectorOpts struct {
	Namespace string
	PidFn     func() (int, error)
}

ProcessCollectorOpts are options for the process collector

type PushOpts added in v1.4.11

type PushOpts struct {
	URL      string
	Job      string
	Instance string
	Gatherer Gatherer
	Client   *http.Client
	Timeout  time.Duration
}

PushOpts configures a metrics push request.

type Quantile added in v1.4.11

type Quantile struct {
	Quantile float64
	Value    float64
}

Quantile represents a summary quantile.

type Registerer

type Registerer interface {
	Metrics
	Register(Collector) error
	MustRegister(...Collector)
}

Registerer is the minimal interface required to register and create metrics.

type Registry

type Registry interface {
	Registerer
	Gatherer
}

Registry is a registerer that can also gather metric families.

var DefaultRegistry Registry = NewRegistry()

DefaultRegistry is the default in-process registry used by package-level helpers.

func MakeAndRegister

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

MakeAndRegister creates a new registry and registers it with the gatherer.

func NewNoOpRegistry

func NewNoOpRegistry() Registry

NewNoOpRegistry returns a no-op registry.

func NewRegistry

func NewRegistry() Registry

NewRegistry returns a no-op registry when metrics are disabled.

type Request

type Request interface {
	Context() context.Context
	Method() string
	URL() string
}

Request represents an HTTP request.

type ResponseWriter

type ResponseWriter interface {
	Write([]byte) (int, error)
	WriteHeader(int)
	Header() map[string][]string
}

ResponseWriter is an interface for writing HTTP responses.

type Set added in v1.4.11

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

Set groups metrics under a shared registry.

This is a thin wrapper around Registry to provide a single place to create and export a collection of metrics.

func NewSet added in v1.4.11

func NewSet() *Set

NewSet creates a new metrics set backed by its own registry.

func (*Set) NewCounter added in v1.4.11

func (s *Set) NewCounter(name, help string) Counter

NewCounter registers and returns a counter in the set.

func (*Set) NewCounterVec added in v1.4.11

func (s *Set) NewCounterVec(name, help string, labelNames []string) CounterVec

NewCounterVec registers and returns a counter vector in the set.

func (*Set) NewGauge added in v1.4.11

func (s *Set) NewGauge(name, help string) Gauge

NewGauge registers and returns a gauge in the set.

func (*Set) NewGaugeVec added in v1.4.11

func (s *Set) NewGaugeVec(name, help string, labelNames []string) GaugeVec

NewGaugeVec registers and returns a gauge vector in the set.

func (*Set) NewHistogram added in v1.4.11

func (s *Set) NewHistogram(name, help string, buckets []float64) Histogram

NewHistogram registers and returns a histogram in the set.

func (*Set) NewHistogramVec added in v1.4.11

func (s *Set) NewHistogramVec(name, help string, labelNames []string, buckets []float64) HistogramVec

NewHistogramVec registers and returns a histogram vector in the set.

func (*Set) NewSummary added in v1.4.11

func (s *Set) NewSummary(name, help string, objectives map[float64]float64) Summary

NewSummary registers and returns a summary in the set.

func (*Set) NewSummaryVec added in v1.4.11

func (s *Set) NewSummaryVec(name, help string, labelNames []string, objectives map[float64]float64) SummaryVec

NewSummaryVec registers and returns a summary vector in the set.

func (*Set) Registry added in v1.4.11

func (s *Set) Registry() Registry

Registry returns the underlying registry.

func (*Set) Write added in v1.4.11

func (s *Set) Write(w io.Writer) error

Write writes the set metrics to w in the text exposition format.

type Summary

type Summary interface {
	Observe(float64)
}

Summary captures individual observations and provides quantiles.

func NewNoopSummary

func NewNoopSummary() Summary

NewNoopSummary returns a no-op summary.

func NewSummary

func NewSummary(opts SummaryOpts) Summary

NewSummary creates a new summary with the given options.

type SummaryOpts

type SummaryOpts struct {
	Namespace   string
	Subsystem   string
	Name        string
	Help        string
	ConstLabels Labels
	Objectives  map[float64]float64
}

SummaryOpts configures a summary metric.

type SummaryVec

type SummaryVec interface {
	With(Labels) Summary
	WithLabelValues(...string) Summary
}

SummaryVec is a labeled summary collection.

func NewSummaryVec

func NewSummaryVec(opts SummaryOpts, labelNames []string) SummaryVec

NewSummaryVec creates a new summary vector with the given options.

type TextParser added in v1.4.5

type TextParser struct{}

TextParser parses the metrics text format.

func (*TextParser) TextToMetricFamilies added in v1.4.11

func (p *TextParser) TextToMetricFamilies(r io.Reader) (map[string]*MetricFamily, error)

TextToMetricFamilies parses text format into metric families.

type Timer

type Timer interface {
	Start() func()
	ObserveTime(time.Duration)
}

Timer measures durations.

type TimingMetric added in v1.4.10

type TimingMetric = timingMetric

TimingMetric measures durations and records them in a histogram.

func NewTimingMetric added in v1.4.10

func NewTimingMetric(histogram Histogram) *TimingMetric

NewTimingMetric creates a timing metric bound to the provided histogram.

Directories

Path Synopsis
Package profiler provides CPU, memory, and lock profiling utilities.
Package profiler provides CPU, memory, and lock profiling utilities.

Jump to

Keyboard shortcuts

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