metrics

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package metrics provides Prometheus metrics collection with standardized naming conventions and automatic HTTP/gRPC middleware for observability. It supports counters, gauges, and histograms with label validation and duplicate prevention.

Example usage:

// Initialize metrics with configuration
if err := metrics.Init(cfg.Metrics); err != nil {
    log.Fatal(err)
}
defer metrics.Shutdown(context.Background())

// Create a custom counter
counter := metrics.NewCounter(metrics.CounterOpts{
    Namespace: "myapp",
    Subsystem: "orders",
    Name:      "total",
    Help:      "Total number of orders processed",
    Labels:    []string{"status", "region"},
})
counter.WithLabelValues("completed", "us-west").Inc()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HTTPMiddleware

func HTTPMiddleware(namespace string) func(http.Handler) http.Handler

HTTPMiddleware is an HTTP middleware that automatically records standard metrics for HTTP requests including duration, count, request size, and response size. It initializes standard metrics on first use with the provided namespace.

func Init

func Init(cfg MetricsConfig) error

Init initializes the metrics system with the provided configuration. It creates a new Prometheus registry and starts an HTTP server on the configured port and path to expose metrics.

This function is safe to call multiple times - subsequent calls are no-ops. Returns an error if the metrics system cannot be initialized (e.g., port already in use).

func InitStandardMetrics

func InitStandardMetrics(namespace string) error

InitStandardMetrics initializes standard HTTP and gRPC metrics. This function is called automatically by the middleware, but can be called explicitly to ensure metrics are registered before use. It is safe to call multiple times - subsequent calls are no-ops.

func IsInitialized

func IsInitialized() bool

IsInitialized returns true if Init() has been called successfully.

func Registry

func Registry() *prometheus.Registry

Registry returns the global Prometheus registry. This is useful for custom metric registration or testing. Returns nil if Init() has not been called.

func Shutdown

func Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the metrics HTTP server. It waits for up to the context deadline for in-flight requests to complete.

func StreamServerInterceptor

func StreamServerInterceptor(namespace string) grpc.StreamServerInterceptor

StreamServerInterceptor is a gRPC stream server interceptor that automatically records standard metrics for gRPC streaming calls including duration and count. It initializes standard metrics on first use with the provided namespace.

func UnaryServerInterceptor

func UnaryServerInterceptor(namespace string) grpc.UnaryServerInterceptor

UnaryServerInterceptor is a gRPC unary server interceptor that automatically records standard metrics for gRPC calls including duration and count. It initializes standard metrics on first use with the provided namespace.

Types

type Counter

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

Counter is a Prometheus counter that can only increase.

func GetGRPCCallCount

func GetGRPCCallCount() *Counter

GetGRPCCallCount returns the standard gRPC call count counter. Returns nil if standard metrics have not been initialized.

func GetHTTPRequestCount

func GetHTTPRequestCount() *Counter

GetHTTPRequestCount returns the standard HTTP request count counter. Returns nil if standard metrics have not been initialized.

func NewCounter

func NewCounter(opts CounterOpts) (*Counter, error)

NewCounter creates and registers a new counter with the global registry. The full metric name will be "{namespace}_{subsystem}_{name}". Returns an error if the metric name or labels are invalid, or if a metric with the same name is already registered.

func (*Counter) Add

func (c *Counter) Add(value float64, labelValues ...string)

Add increments the counter by the given value for the given label values. The value must be non-negative.

func (*Counter) Inc

func (c *Counter) Inc(labelValues ...string)

Inc increments the counter by 1 for the given label values.

func (*Counter) WithLabelValues

func (c *Counter) WithLabelValues(labelValues ...string) prometheus.Counter

WithLabelValues returns a counter for the given label values. This allows more efficient access when incrementing the same labels repeatedly.

type CounterOpts

type CounterOpts struct {
	Namespace string   // Metric namespace (e.g., "cqi", "myapp")
	Subsystem string   // Metric subsystem (e.g., "http", "database")
	Name      string   // Metric name (e.g., "requests_total")
	Help      string   // Human-readable help text
	Labels    []string // Label names for this metric
}

CounterOpts specifies options for creating a counter.

type Gauge

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

Gauge is a Prometheus gauge that can increase or decrease.

func NewGauge

func NewGauge(opts GaugeOpts) (*Gauge, error)

NewGauge creates and registers a new gauge with the global registry. The full metric name will be "{namespace}_{subsystem}_{name}". Returns an error if the metric name or labels are invalid, or if a metric with the same name is already registered.

func (*Gauge) Add

func (g *Gauge) Add(value float64, labelValues ...string)

Add adds the given value to the gauge for the given label values.

func (*Gauge) Dec

func (g *Gauge) Dec(labelValues ...string)

Dec decrements the gauge by 1 for the given label values.

func (*Gauge) Inc

func (g *Gauge) Inc(labelValues ...string)

Inc increments the gauge by 1 for the given label values.

func (*Gauge) Set

func (g *Gauge) Set(value float64, labelValues ...string)

Set sets the gauge to the given value for the given label values.

func (*Gauge) Sub

func (g *Gauge) Sub(value float64, labelValues ...string)

Sub subtracts the given value from the gauge for the given label values.

func (*Gauge) WithLabelValues

func (g *Gauge) WithLabelValues(labelValues ...string) prometheus.Gauge

WithLabelValues returns a gauge for the given label values. This allows more efficient access when updating the same labels repeatedly.

type GaugeOpts

type GaugeOpts struct {
	Namespace string   // Metric namespace (e.g., "cqi", "myapp")
	Subsystem string   // Metric subsystem (e.g., "http", "database")
	Name      string   // Metric name (e.g., "connections_active")
	Help      string   // Human-readable help text
	Labels    []string // Label names for this metric
}

GaugeOpts specifies options for creating a gauge.

type Histogram

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

Histogram is a Prometheus histogram that samples observations.

func GetGRPCCallDuration

func GetGRPCCallDuration() *Histogram

GetGRPCCallDuration returns the standard gRPC call duration histogram. Returns nil if standard metrics have not been initialized.

func GetHTTPRequestDuration

func GetHTTPRequestDuration() *Histogram

GetHTTPRequestDuration returns the standard HTTP request duration histogram. Returns nil if standard metrics have not been initialized.

func GetHTTPRequestSize

func GetHTTPRequestSize() *Histogram

GetHTTPRequestSize returns the standard HTTP request size histogram. Returns nil if standard metrics have not been initialized.

func GetHTTPResponseSize

func GetHTTPResponseSize() *Histogram

GetHTTPResponseSize returns the standard HTTP response size histogram. Returns nil if standard metrics have not been initialized.

func NewHistogram

func NewHistogram(opts HistogramOpts) (*Histogram, error)

NewHistogram creates and registers a new histogram with the global registry. The full metric name will be "{namespace}_{subsystem}_{name}". Returns an error if the metric name or labels are invalid, or if a metric with the same name is already registered.

func (*Histogram) Observe

func (h *Histogram) Observe(value float64, labelValues ...string)

Observe adds an observation to the histogram for the given label values.

func (*Histogram) WithLabelValues

func (h *Histogram) WithLabelValues(labelValues ...string) prometheus.Observer

WithLabelValues returns a histogram observer for the given label values. This allows more efficient access when observing the same labels repeatedly.

type HistogramOpts

type HistogramOpts struct {
	Namespace string    // Metric namespace (e.g., "cqi", "myapp")
	Subsystem string    // Metric subsystem (e.g., "http", "database")
	Name      string    // Metric name (e.g., "request_duration_seconds")
	Help      string    // Human-readable help text
	Labels    []string  // Label names for this metric
	Buckets   []float64 // Histogram buckets (use nil for default)
}

HistogramOpts specifies options for creating a histogram.

type MetricsConfig

type MetricsConfig struct {
	Enabled   bool   // Whether metrics collection is enabled
	Port      int    // HTTP server port for /metrics endpoint
	Path      string // HTTP path for metrics endpoint
	Namespace string // Metric prefix/namespace
}

MetricsConfig contains Prometheus metrics configuration.

func DefaultMetricsConfig

func DefaultMetricsConfig() MetricsConfig

DefaultMetricsConfig returns a MetricsConfig with sensible defaults.

Jump to

Keyboard shortcuts

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