collector

package
v2.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: EUPL-1.2 Imports: 15 Imported by: 0

Documentation

Overview

Package collector provides interfaces and implementations for pull-based metric collection.

Unlike regular metrics that are updated throughout the application lifetime, collectors compute their values on-demand when metrics are scraped. This is useful for metrics that are expensive to compute or that represent external system state (process metrics, runtime statistics, etc.).

Collector Interface

The Collector interface is intentionally minimal, requiring only:

  • io.WriterTo for zero-copy serialization to OpenMetrics format
  • Name() for unique identification in the registry

This design maintains epimetheus's zero-copy philosophy: collectors write directly to the output without intermediate allocations.

Built-in Collectors

The package provides two ready-to-use collectors:

  • ProcessCollector: process-level metrics (CPU, memory, file descriptors) — platform-aware (darwin, linux)
  • GoRuntimeCollector: Go runtime metrics (goroutines, memory stats, GC)

Custom Collectors (callback-based)

For external integrations, the package provides callback-based adapters that handle OpenMetrics formatting automatically:

  • GaugeFunc: gauge metric computed on demand via func() float64
  • CounterFunc: counter metric computed on demand via func() uint64
  • InfoFunc: info metric with dynamic labels via func() label.Labels
  • Group: composition of multiple collectors under a single name

These adapters validate inputs at construction time (metric name, help text, label names/values) and manage pooled buffers for zero-copy serialization. The callback contract: functions must not panic — no recover is performed, consistent with the rest of epimetheus.

Usage

reg := registry.New()

// Register built-in collectors
reg.RegisterCollector(collector.NewProcessCollector())
reg.RegisterCollector(collector.NewGoRuntimeCollector())

// Register a custom gauge
g, _ := collector.NewGaugeFunc("pool_size", "Current pool size.",
    label.Pairs{label.L("pool", "db")},
    func() float64 { return float64(pool.Size()) },
)
reg.RegisterCollector(g)

// Register a custom counter
c, _ := collector.NewCounterFunc("cache_hits", "Total cache hits.", nil,
    func() uint64 { return cache.Hits() },
)
reg.RegisterCollector(c)

// Register build info
i, _ := collector.NewInfoFunc("build", "Build information.",
    func() label.Labels {
        return label.Pairs{label.L("version", version), label.L("go", runtime.Version())}
    },
)
reg.RegisterCollector(i)

Français

Le package collector fournit des interfaces et implémentations pour la collecte de métriques à la demande (pull-based).

Contrairement aux métriques régulières qui sont mises à jour tout au long de la vie de l'application, les collectors calculent leurs valeurs à la demande lors du scraping. C'est utile pour les métriques coûteuses à calculer ou représentant l'état de systèmes externes.

L'interface Collector est volontairement minimale :

  • io.WriterTo pour la sérialisation zero-copy en format OpenMetrics
  • Name() pour l'identification unique dans le registre

Les adaptateurs callback (GaugeFunc, CounterFunc, InfoFunc, Group) permettent de créer des collectors personnalisés sans écrire du formatage OpenMetrics à la main. Toutes les validations sont effectuées à la construction.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Collector

type Collector interface {
	// WriteTo writes all collected metrics in OpenMetrics format.
	// The output should NOT include the # EOF marker.
	io.WriterTo

	// Name returns a unique identifier for this collector.
	// Used to prevent duplicate registration.
	Name() string
}

Collector gathers metrics on demand. It writes directly in OpenMetrics format for zero-copy performance.

Collectors are registered with a Registry and invoked during WriteTo. Each collector must have a unique name to prevent duplicates.

Collector rassemble des métriques à la demande. Il écrit directement en format OpenMetrics pour une performance zero-copy.

func NewCounterFunc

func NewCounterFunc(name, help string, labels label.Labels, fn func() uint64, opts ...metric.MetricConfig) (Collector, error)

NewCounterFunc creates a new CounterFunc collector. The name must be a valid OpenMetrics metric name. The help text must not contain newlines. Labels, if provided, are validated at construction. The callback fn must not be nil. The _created timestamp is captured at construction time.

The callback function must not panic. If it does, the entire metrics scrape will fail. Use recover in your callback if calling unreliable code.

func NewGaugeFunc

func NewGaugeFunc(name, help string, labels label.Labels, fn func() float64, opts ...metric.MetricConfig) (Collector, error)

NewGaugeFunc creates a new GaugeFunc collector. The name must be a valid OpenMetrics metric name. The help text must not contain newlines. Labels, if provided, are validated at construction. The callback fn must not be nil.

The callback function must not panic. If it does, the entire metrics scrape will fail. Use recover in your callback if calling unreliable code.

Example
package main

import (
	"bytes"
	"fmt"
	"strings"

	"codeberg.org/nathanaelle/epimetheus/v2/collector"
)

func main() {
	// GaugeFunc computes its value on demand via a callback
	gf, err := collector.NewGaugeFunc(
		"build_info_ready",
		"Whether the service is ready",
		nil,
		func() float64 { return 1 },
	)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	var buf bytes.Buffer
	gf.WriteTo(&buf)

	for line := range strings.SplitSeq(buf.String(), "\n") {
		if line != "" {
			fmt.Println(line)
		}
	}

}
Output:
# TYPE build_info_ready gauge
# HELP build_info_ready Whether the service is ready
build_info_ready 1

func NewGroup

func NewGroup(name string, collectors ...Collector) (Collector, error)

NewGroup creates a new Group collector. The name must be non-empty. No nil collectors are allowed. An empty group (no collectors) is valid and writes nothing.

func NewInfoFunc

func NewInfoFunc(name, help string, fn func() label.Labels, opts ...metric.MetricConfig) (Collector, error)

NewInfoFunc creates a new InfoFunc collector. The name must be a valid OpenMetrics metric name. The help text must not contain newlines. The callback fn must not be nil. It returns dynamic labels evaluated at scrape time.

Labels returned by the callback are not validated at scrape time. The caller is responsible for returning valid label names and values. Invalid labels will produce malformed OpenMetrics output.

The callback function must not panic. If it does, the entire metrics scrape will fail. Use recover in your callback if calling unreliable code.

type CounterFunc

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

CounterFunc is a Collector that computes a counter value on demand via a callback. The callback returns a uint64 (counters are monotonically increasing non-negative). Labels are fixed at construction. A _created timestamp is captured at construction time.

The callback contract:

  • Must not panic (no recover is performed).
  • Must be safe for concurrent calls if WriteTo is called concurrently.
  • Must return a monotonically increasing value.

CounterFunc est un Collector qui calcule une valeur compteur à la demande via un callback. Le callback retourne un uint64 (les compteurs sont monotoniquement croissants, non-négatifs).

func (*CounterFunc) Name

func (c *CounterFunc) Name() string

Name returns the metric name, used as collector identifier.

func (*CounterFunc) WriteTo

func (c *CounterFunc) WriteTo(w io.Writer) (int64, error)

WriteTo writes the counter metric in OpenMetrics format. Includes _total (value) and _created (timestamp) lines per OpenMetrics spec.

type GaugeFunc

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

GaugeFunc is a Collector that computes a gauge value on demand via a callback. The callback is invoked at each WriteTo call. Labels are fixed at construction.

The callback contract:

  • Must not panic (no recover is performed).
  • Must be safe for concurrent calls if WriteTo is called concurrently.

GaugeFunc est un Collector qui calcule une valeur gauge à la demande via un callback. Le callback est invoqué à chaque appel WriteTo. Les labels sont fixés à la construction.

func (*GaugeFunc) Name

func (g *GaugeFunc) Name() string

Name returns the metric name, used as collector identifier.

func (*GaugeFunc) WriteTo

func (g *GaugeFunc) WriteTo(w io.Writer) (int64, error)

WriteTo writes the gauge metric in OpenMetrics format. The callback is invoked to get the current value.

type GoRuntimeCollector

type GoRuntimeCollector struct{}

GoRuntimeCollector collects Go runtime metrics. All metrics are computed on-demand during WriteTo.

Metrics include:

  • go_goroutines: number of goroutines
  • go_threads: number of OS threads created
  • go_gc_duration_seconds: GC pause duration summary
  • go_memstats_*: various memory statistics
  • go_info: Go version information as a gauge with labels

GoRuntimeCollector collecte les métriques du runtime Go. Toutes les métriques sont calculées à la demande lors de WriteTo.

func NewGoRuntimeCollector

func NewGoRuntimeCollector() *GoRuntimeCollector

NewGoRuntimeCollector creates a new GoRuntimeCollector.

func (*GoRuntimeCollector) Name

func (g *GoRuntimeCollector) Name() string

Name returns "go" as the collector identifier.

func (*GoRuntimeCollector) WriteTo

func (g *GoRuntimeCollector) WriteTo(w io.Writer) (int64, error)

WriteTo writes Go runtime metrics in OpenMetrics format.

type Group

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

Group is a Collector that composes multiple sub-collectors. It delegates WriteTo to each sub-collector sequentially, in order. Each sub-collector manages its own buffering and formatting.

Group est un Collector qui compose plusieurs sous-collectors. Il délègue WriteTo à chaque sous-collector séquentiellement, dans l'ordre.

func (*Group) Name

func (g *Group) Name() string

Name returns the group name, used as collector identifier.

func (*Group) WriteTo

func (g *Group) WriteTo(w io.Writer) (int64, error)

WriteTo writes all sub-collector metrics sequentially. Short-circuits on the first error, returning the total bytes written so far.

type InfoFunc

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

InfoFunc is a Collector that produces an info metric with dynamic labels. The callback returns label.Labels that are serialized on each WriteTo call. Info metrics always have value 1 and use the _info suffix per OpenMetrics spec.

Unlike GaugeFunc/CounterFunc, labels are dynamic (computed by the callback), so they cannot be validated at construction time.

The callback contract:

  • Must not panic (no recover is performed).
  • Must be safe for concurrent calls if WriteTo is called concurrently.
  • Must return a fresh Labels instance or one safe for concurrent read access.

InfoFunc est un Collector qui produit une métrique info avec des labels dynamiques. Le callback retourne des label.Labels sérialisés à chaque appel WriteTo.

func (*InfoFunc) Name

func (i *InfoFunc) Name() string

Name returns the metric name, used as collector identifier.

func (*InfoFunc) WriteTo

func (i *InfoFunc) WriteTo(w io.Writer) (int64, error)

WriteTo writes the info metric in OpenMetrics format. The callback is invoked to get current labels. Output format: TYPE info, HELP, name_info{labels} 1

type ProcessCollector

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

ProcessCollector collects process-level metrics. Metrics are computed on-demand during WriteTo.

On Linux: reads from /proc/self for accurate process information. On Darwin (macOS): uses syscalls for available metrics. On other platforms: provides partial metrics from Go runtime.

ProcessCollector collecte les métriques au niveau processus. Les métriques sont calculées à la demande lors de WriteTo.

func NewProcessCollector

func NewProcessCollector() *ProcessCollector

NewProcessCollector creates a new ProcessCollector.

func (*ProcessCollector) Name

func (p *ProcessCollector) Name() string

Name returns "process" as the collector identifier.

func (*ProcessCollector) WriteTo

func (p *ProcessCollector) WriteTo(w io.Writer) (int64, error)

WriteTo writes process metrics in OpenMetrics format. Implementation is platform-specific via build tags.

Jump to

Keyboard shortcuts

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