metrics

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package metrics provides Prometheus-based monitoring and metrics collection functionality for Go applications.

The metrics package is designed to provide a standardized observability approach with features such as configurable HTTP endpoints for metrics exposure, automatic runtime instrumentation, and integration with the Fx dependency injection framework for easy incorporation into Aleph Alpha services.

Core Features:

  • Exposes a configurable /metrics endpoint for Prometheus scraping
  • Integration with go.uber.org/fx for automatic lifecycle management
  • Automatic registration of Go runtime and process-level metrics
  • Support for custom metric registration (counters, gauges, histograms)
  • Optional namespace and service name labelling for multi-service observability
  • Graceful startup and shutdown via Fx lifecycle hooks

Basic Usage:

import "github.com/Aleph-Alpha/std/v1/metrics"

// Create a new metrics server manually
cfg := metrics.Config{
	Address:                ":9090",
	EnableDefaultCollectors: true,
	ServiceName:             "search-store",
	Namespace:               "pharia_data",
}

m := metrics.NewMetrics(cfg)
go m.Server.ListenAndServe()

// Register custom counters
counter := prometheus.NewCounterVec(
    prometheus.CounterOpts{
        Name: "http_requests_total",
        Help: "Total number of HTTP requests processed.",
    },
    []string{"method", "endpoint"},
)
m.Registry.MustRegister(counter)

FX Module Integration:

This package provides an Fx module for easy integration with applications using the Fx dependency injection framework:

app := fx.New(
	logger.FXModule,
	metrics.FXModule,
	fx.Provide(func() metrics.Config {
		return metrics.Config{
			Address:                ":9090",
			EnableDefaultCollectors: true,
			ServiceName:             "search-store",
		}
	}),
)
app.Run()

Configuration:

The metrics server can be configured via environment variables:

METRICS_ADDRESS=:9090                      # Port and address for /metrics endpoint
METRICS_ENABLE_DEFAULT_COLLECTORS=true     # Enable runtime and process metrics
METRICS_NAMESPACE=pharia_data              # Optional prefix for all metric names
METRICS_SERVICE_NAME=search-store          # Adds service label to all metrics

Default Collectors:

When EnableDefaultCollectors is true, the package automatically registers the following collectors:

  • Go runtime metrics (goroutines, GC stats, heap usage)
  • Process metrics (CPU time, memory, file descriptors)

These metrics provide deep visibility into service performance and stability.

Custom Metrics:

Applications can register additional Prometheus metrics using the exposed Registry. For example:

requestDuration := prometheus.NewHistogramVec(
    prometheus.HistogramOpts{
        Name:    "http_request_duration_seconds",
        Help:    "Histogram of request latencies.",
        Buckets: prometheus.DefBuckets,
    },
    []string{"method", "route"},
)
m.Registry.MustRegister(requestDuration)

Performance Considerations:

The metrics server runs in a separate HTTP handler and is lightweight. Default collectors use minimal resources, but avoid unnecessary high-cardinality metrics or unbounded label values to maintain good performance.

Thread Safety:

All methods on the Metrics struct and Prometheus collectors are safe for concurrent use by multiple goroutines.

Observability:

Exposed metrics can be visualized in Prometheus, Grafana, or any compatible monitoring system to provide insights into service health, latency, and resource utilization.

Index

Constants

View Source
const DefaultMetricsAddress = ":9090"

Default port for metrics server if none is specified.

Variables

FXModule defines the Fx module for the metrics package. This module integrates the Prometheus metrics server into an Fx-based application by providing the Metrics factory and registering its lifecycle hooks.

The module:

  1. Provides the NewMetrics factory function to the dependency injection container, making the Metrics instance available to other components.
  2. Invokes RegisterMetricsLifecycle to manage startup and graceful shutdown of the Prometheus HTTP server.

Usage:

app := fx.New(
    metrics.FXModule,
    fx.Provide(func() metrics.Config {
        return metrics.Config{
            Address:                ":9090",
            EnableDefaultCollectors: true,
            ServiceName:             "search-store",
        }
    }),
    // other modules...
)

Dependencies required by this module: - A metrics.Config instance must be available in the dependency injection container - A logger.Logger instance is optional but recommended for startup/shutdown logs

Functions

func RegisterMetricsLifecycle

func RegisterMetricsLifecycle(lc fx.Lifecycle, m *Metrics, log *logger.Logger)

RegisterMetricsLifecycle manages the startup and shutdown lifecycle of the Prometheus metrics HTTP server.

Parameters:

  • lc: The Fx lifecycle controller
  • m: The Metrics instance containing the HTTP server
  • log: The logger instance for structured lifecycle logging (optional)

The lifecycle hook:

  • OnStart: Launches the Prometheus HTTP server in a background goroutine.
  • OnStop: Gracefully shuts down the metrics server.

This ensures that metrics are available for scraping during the application's lifetime and that the server shuts down cleanly when the application stops.

Note: This function is automatically invoked by the FXModule and does not need to be called directly in application code.

Types

type Config

type Config struct {
	// Address determines the network address where the Prometheus
	// metrics HTTP server listens.
	//
	// Example values:
	//   - ":9090"   → Listen on all interfaces, port 9090
	//   - "127.0.0.1:9100" → Listen only on localhost, port 9100
	//
	// This setting can be configured via:
	//   - YAML configuration with the "address" key
	//   - Environment variable METRICS_ADDRESS
	//
	// Default: ":9090"
	Address string `yaml:"address" envconfig:"METRICS_ADDRESS"`

	// EnableDefaultCollectors controls whether the built-in Go runtime
	// and process metrics are automatically registered.
	//
	// When true, metrics such as goroutine count, GC stats, and CPU usage
	// will be included automatically. Disable only if you want full
	// manual control over registered collectors.
	//
	// This setting can be configured via:
	//   - YAML configuration with the "enable_default_collectors" key
	//   - Environment variable METRICS_ENABLE_DEFAULT_COLLECTORS
	//
	// Default: true
	EnableDefaultCollectors bool `yaml:"enable_default_collectors" envconfig:"METRICS_ENABLE_DEFAULT_COLLECTORS"`

	// Namespace sets a global prefix for all metrics registered by this service.
	// Useful when running multiple services in the same Prometheus cluster.
	//
	// Example:
	//   Namespace: "pharia_data"
	//   → Metric name becomes "pharia_data_http_requests_total"
	//
	// This setting can be configured via:
	//   - YAML configuration with the "namespace" key
	//   - Environment variable METRICS_NAMESPACE
	Namespace string `yaml:"namespace" envconfig:"METRICS_NAMESPACE"`

	// ServiceName identifies the service exposing metrics.
	// This is used as a common label in all metrics to help
	// distinguish metrics between services in multi-tenant deployments.
	//
	// Example:
	//   ServiceName: "document-index"
	//   → metrics include label service="document-index"
	//
	// This setting can be configured via:
	//   - YAML configuration with the "service_name" key
	//   - Environment variable METRICS_SERVICE_NAME
	ServiceName string `yaml:"service_name" envconfig:"METRICS_SERVICE_NAME"`
}

Config defines the configuration structure for the Prometheus metrics server. It contains settings that control how metrics are exposed and collected.

type Metrics

type Metrics struct {
	// Server defines the HTTP server used to expose the /metrics endpoint.
	Server *http.Server

	// Registry is the Prometheus registry where all metrics are registered.
	// Each service maintains its own isolated registry to prevent metric name collisions.
	Registry *prometheus.Registry
	// contains filtered or unexported fields
}

Metrics encapsulates the Prometheus registry and HTTP server responsible for exposing application metrics.

This structure provides the components needed to register metrics collectors and serve them via the /metrics HTTP endpoint for Prometheus scraping.

func NewMetrics

func NewMetrics(cfg Config) *Metrics

NewMetrics initializes and returns a new instance of the Metrics struct. It sets up a dedicated Prometheus registry, registers default system collectors, wraps all metrics with a constant `service` label, and creates an HTTP server exposing the /metrics endpoint.

Parameters:

  • cfg: Configuration for the metrics server, including listening address, service name, and whether to enable default collectors.

Returns:

  • *Metrics: A configured Metrics instance ready for lifecycle management and Fx module integration.

The setup includes:

  • A dedicated Prometheus registry for the service
  • Automatic registration of Go, process, and build info collectors
  • A global "service" label applied to all metrics for easier aggregation
  • An HTTP server exposing the metrics endpoint

Example:

cfg := metrics.Config{
    Address:              ":9090",
    ServiceName:           "document-index",
    EnableDefaultCollectors: true,
}
metricsInstance := metrics.NewMetrics(cfg)
go metricsInstance.Server.ListenAndServe()

Access metrics at: http://localhost:9090/metrics

func (*Metrics) CreateCounter

func (m *Metrics) CreateCounter(name, help string, labels []string) *prometheus.CounterVec

Dynamic metric factories CreateCounter creates a new CounterVec metric and registers it.

func (*Metrics) CreateGauge

func (m *Metrics) CreateGauge(name, help string, labels []string) *prometheus.GaugeVec

CreateGauge creates a new GaugeVec metric and registers it.

func (*Metrics) CreateHistogram

func (m *Metrics) CreateHistogram(name, help string, labels []string, buckets []float64) *prometheus.HistogramVec

CreateHistogram creates a new HistogramVec metric and registers it.

func (*Metrics) IncrementRequests

func (m *Metrics) IncrementRequests(status string)

Default metric methods IncrementRequests increments the request counter with a given status label. Example: metrics.IncrementRequests("success")

func (*Metrics) ObserveCPUUsage

func (m *Metrics) ObserveCPUUsage(value float64, core string)

ObserveCPUUsage sets the CPU usage gauge for a given core. Example: metrics.ObserveCPUUsage(87.2, "core_0")

func (*Metrics) RecordRequestDuration

func (m *Metrics) RecordRequestDuration(start time.Time, endpoint string)

RecordRequestDuration records the duration (in seconds) for a request endpoint. Example: defer metrics.RecordRequestDuration(time.Now(), "/search")

Jump to

Keyboard shortcuts

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