Documentation
¶
Overview ¶
Package metric provides metrics collection. Designed for minimal allocations and standalone operation.
Index ¶
- Constants
- Variables
- func AppendNamespace(namespace, name string) string
- func EncodeText(w io.Writer, families []*MetricFamily) error
- func ExponentialBuckets(start, factor float64, count int) []float64
- func HTTPHandler(gatherer Gatherer, opts HandlerOpts) http.Handler
- func Handler() http.Handler
- func HandlerFor(gatherer Gatherer) http.Handler
- func HandlerForWithOpts(gatherer Gatherer, opts HandlerOpts) http.Handler
- func IsValidLabelName(name string) bool
- func IsValidMetricName(name string) bool
- func LinearBuckets(start, width float64, count int) []float64
- func NewHTTPHandler(gatherer Gatherer, opts HandlerOpts) http.Handler
- func ParseText(r io.Reader) (map[string]*MetricFamily, error)
- func Push(opts PushOpts) error
- func SetFactory(factory Factory)
- func ValidateGatherer(gatherer Gatherer) error
- func ValidateLabelName(name string) error
- func ValidateLabels(labels Labels) error
- func ValidateMetricName(name string) error
- func WriteGoMetrics(w io.Writer) error
- func WriteProcessMetrics(w io.Writer) error
- type APIInterceptor
- type Averager
- type Bucket
- type BucketWire
- type Client
- type Collector
- type Counter
- type CounterOpts
- type CounterVec
- type Errs
- type Factory
- type Gatherer
- type Gatherers
- type Gauge
- type GaugeOpts
- type GaugeVec
- type HTTPHandlerOpts
- type HandlerErrorHandling
- type HandlerOpts
- type Histogram
- type HistogramOpts
- type HistogramVec
- type LabelPair
- type Labels
- type Metric
- type MetricBatch
- type MetricDesc
- type MetricFamilies
- type MetricFamily
- type MetricFamilyWire
- type MetricType
- type MetricValue
- type MetricWire
- type Metrics
- type MetricsHTTPHandler
- type MultiGatherer
- type ProcessCollectorOpts
- type PushOpts
- type Quantile
- type QuantileWire
- type Registerer
- type Registry
- type Request
- type ResponseWriter
- type Set
- func (s *Set) NewCounter(name, help string) Counter
- func (s *Set) NewCounterVec(name, help string, labelNames []string) CounterVec
- func (s *Set) NewGauge(name, help string) Gauge
- func (s *Set) NewGaugeVec(name, help string, labelNames []string) GaugeVec
- func (s *Set) NewHistogram(name, help string, buckets []float64) Histogram
- func (s *Set) NewHistogramVec(name, help string, labelNames []string, buckets []float64) HistogramVec
- func (s *Set) NewSummary(name, help string, objectives map[float64]float64) Summary
- func (s *Set) NewSummaryVec(name, help string, labelNames []string, objectives map[float64]float64) SummaryVec
- func (s *Set) Registry() Registry
- func (s *Set) Write(w io.Writer) error
- type Summary
- type SummaryOpts
- type SummaryVec
- type TextParser
- type Timer
- type TimingMetric
- type ZAPExporter
- type ZAPExporterConfig
Constants ¶
const ( NamespaceSeparatorByte = '_' NamespaceSeparator = string(NamespaceSeparatorByte) )
const MsgMetricBatch uint16 = 2
MsgMetricBatch is the ZAP MsgType that carries a MetricBatch payload.
Stable wire ID for the metric transport on the ZAP bus. Append-only — renumbering breaks every deployed collector in lockstep. Coordinates with luxfi/trace.MsgSpanBatch (=1); collectors switch on the MsgType-in-flags-upper-byte to route to the right ingest path.
Variables ¶
var DefBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}
DefBuckets defines default histogram buckets.
var ErrFailedRegistering = errors.New("failed registering metric")
Functions ¶
func AppendNamespace ¶
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 ExponentialBuckets ¶ added in v1.5.4
ExponentialBuckets returns count buckets whose upper bounds are start*factor^i for i in [0, count). Mirrors prometheus/client_golang's ExponentialBuckets so call sites can migrate without recomputing bucket arrays. Panics if start <= 0, factor <= 1, or count < 1.
func HTTPHandler ¶
func HTTPHandler(gatherer Gatherer, opts HandlerOpts) http.Handler
HTTPHandler creates an HTTP handler for metrics (compatibility alias).
func HandlerFor ¶
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
IsValidLabelName returns true if name is a valid label name.
func IsValidMetricName ¶ added in v1.4.11
IsValidMetricName returns true if name is a valid metric name.
func LinearBuckets ¶ added in v1.5.4
LinearBuckets returns count buckets each width apart, starting at start. Mirrors prometheus/client_golang's LinearBuckets.
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 ValidateGatherer ¶ added in v1.4.11
ValidateGatherer returns a non-nil error if the gatherer is nil.
func ValidateLabelName ¶ added in v1.4.11
ValidateLabelName validates a label name against the Prometheus text format rules.
func ValidateLabels ¶ added in v1.4.11
ValidateLabels validates all label names in the provided map.
func ValidateMetricName ¶ added in v1.4.11
ValidateMetricName validates a metric name against the Prometheus text format rules.
func WriteGoMetrics ¶ added in v1.4.11
WriteGoMetrics writes Go runtime metrics to w in the text format.
func WriteProcessMetrics ¶ added in v1.4.11
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 BucketWire ¶ added in v1.5.8
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client for requesting metrics from a remote Lux Node instance
func (*Client) GetMetrics ¶
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 ¶
Counter is a metric that can only increase.
func NewCounter ¶
func NewCounter(opts CounterOpts) Counter
NewCounter creates a new counter with the given options.
type CounterOpts ¶
type CounterOpts struct {
Namespace string
Subsystem string
Name string
Help string
ConstLabels Labels
}
CounterOpts configures a counter metric.
type CounterVec ¶
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
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
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 Gauge ¶
type Gauge interface {
Set(float64)
SetToCurrentTime()
Inc()
Dec()
Add(float64)
Sub(float64)
Get() float64
}
Gauge is a metric that can increase or decrease.
type GaugeOpts ¶
type GaugeOpts struct {
Namespace string
Subsystem string
Name string
Help string
ConstLabels Labels
}
GaugeOpts configures a gauge metric.
type GaugeVec ¶
GaugeVec is a labeled gauge collection.
func NewGaugeVec ¶
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 ¶
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 Metric ¶
type Metric struct {
Labels []LabelPair
Value MetricValue
}
Metric represents a single metric with its labels and value.
type MetricBatch ¶ added in v1.5.8
type MetricBatch struct {
AppName string `json:"appName,omitempty"`
Version string `json:"version,omitempty"`
Resource map[string]string `json:"resource,omitempty"`
TimestampNs int64 `json:"timestampNs"`
Families []MetricFamilyWire `json:"families"`
}
MetricBatch is the JSON shape that rides inside the ZAP envelope's payload field. One batch per Export call (typically one Gather() snapshot per scrape interval).
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 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 MetricFamilyWire ¶ added in v1.5.8
type MetricFamilyWire struct {
Name string `json:"name"`
Help string `json:"help,omitempty"`
Type string `json:"type"`
Metrics []MetricWire `json:"metrics"`
}
MetricFamilyWire is the JSON-stable wire shape of a MetricFamily. Mirrors metric.MetricFamily but pins the field names so the collector side can decode without depending on this package's Go types.
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 MetricWire ¶ added in v1.5.8
type MetricWire struct {
Labels map[string]string `json:"labels,omitempty"`
Value *float64 `json:"value,omitempty"` // counter/gauge
SampleCount *uint64 `json:"sampleCount,omitempty"` // histogram/summary
SampleSum *float64 `json:"sampleSum,omitempty"` // histogram/summary
Buckets []BucketWire `json:"buckets,omitempty"` // histogram
Quantiles []QuantileWire `json:"quantiles,omitempty"` // summary
}
MetricWire is the JSON-stable wire shape of a single 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 NewNoOp ¶
func NewNoOp() Metrics
NewNoOp returns a no-op metrics instance without requiring a namespace.
func NewNoOpMetrics ¶
NewNoOpMetrics returns a no-op metrics instance.
func NewWithRegistry ¶
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 ¶
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 QuantileWire ¶ added in v1.5.8
type Registerer ¶
Registerer is the minimal interface required to register and create metrics.
func WrapRegistererWith ¶ added in v1.5.7
func WrapRegistererWith(_ Labels, next Registerer) Registerer
WrapRegistererWith returns a Registerer that attaches the given labels to every metric registered through it. Mirrors prometheus/ client_golang.WrapRegistererWith. Like the prefix variant, the shim passes registrations through without rewriting labels — callers wanting true label-wrapping should embed via ConstLabels.
func WrapRegistererWithPrefix ¶ added in v1.5.7
func WrapRegistererWithPrefix(prefix string, next Registerer) Registerer
WrapRegistererWithPrefix returns a Registerer that prefixes every registered metric's name with prefix before delegating to next. Mirrors prometheus/client_golang.WrapRegistererWithPrefix.
The shim is intentionally minimal: it passes registrations through without rewriting names. Callers who want true prefixing should embed the prefix into the metric's Namespace/Subsystem at creation.
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 NewRegistry ¶
func NewRegistry() Registry
NewRegistry returns a no-op registry when metrics are disabled.
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
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) NewGaugeVec ¶ added in v1.4.11
NewGaugeVec registers and returns a gauge vector in the set.
func (*Set) NewHistogram ¶ added in v1.4.11
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
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.
type Summary ¶
type Summary interface {
Observe(float64)
}
Summary captures individual observations and provides quantiles.
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 ¶
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 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.
type ZAPExporter ¶ added in v1.5.8
type ZAPExporter struct {
// contains filtered or unexported fields
}
ZAPExporter ships metric families over a luxfi/zap connection.
Fire-and-forget by design: tracing and metrics MUST NEVER block the host process. Send failures invalidate the cached connection and trigger a reconnect on the next Export call; no batches are buffered in memory.
func NewZAPExporter ¶ added in v1.5.8
func NewZAPExporter(cfg ZAPExporterConfig) (*ZAPExporter, error)
NewZAPExporter constructs a metric exporter that ships over ZAP.
Returns the exporter even if the initial connect fails — the next Export call will retry. This matches the trace exporter's posture: fire-and-forget means startup never fails on collector reachability.
func (*ZAPExporter) Export ¶ added in v1.5.8
func (e *ZAPExporter) Export(ctx context.Context, families []*MetricFamily) error
Export serializes families to JSON, wraps them in a ZAP envelope, and fires them over the cached connection. Fire-and-forget — no response is expected, no waiting on the collector.
func (*ZAPExporter) ExportGatherer ¶ added in v1.5.8
func (e *ZAPExporter) ExportGatherer(ctx context.Context, g Gatherer) error
ExportGatherer is the convenience entry point — calls Gather() on the supplied Gatherer and ships the resulting families. Use this when driving the exporter from a scrape loop.
type ZAPExporterConfig ¶ added in v1.5.8
type ZAPExporterConfig struct {
// Endpoint is the collector address (host:port). Defaults to
// "127.0.0.1:4317" (the canonical o11y ZAP port).
Endpoint string
// AppName + Version land in every emitted batch's metadata.
AppName string
Version string
// Resource attributes shipped with every batch (e.g., k8s namespace,
// pod name, network ID).
Resource map[string]string
// Logger — defaults to slog.Default().
Logger *slog.Logger
}
ZAPExporterConfig configures the ZAP-native exporter.
Source Files
¶
- api_interceptor.go
- averager.go
- client.go
- collector.go
- def_buckets.go
- defaults_noop.go
- errs.go
- export.go
- exporter_zap.go
- gatherer.go
- go_metrics.go
- handler.go
- metric.go
- metrics_impl.go
- namespace.go
- noop.go
- process_metrics.go
- process_metrics_unix.go
- push.go
- registry_noop.go
- registry_types.go
- set.go
- timing.go
- types.go
- validator.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package io_metric_client provides metric types for Prometheus-compatible metrics.
|
Package io_metric_client provides metric types for Prometheus-compatible metrics. |
|
Package profiler provides CPU, memory, and lock profiling utilities.
|
Package profiler provides CPU, memory, and lock profiling utilities. |