types

package
v1.20.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package types provides core type definitions for Prometheus metrics integration.

This package defines the fundamental interfaces and types used throughout the github.com/nabbar/golib/prometheus ecosystem. It serves as the contract between metric implementations and the Prometheus client library.

Core Components

The package provides:

  • Metric interface: Contract for all metric implementations
  • MetricType: Enumeration of supported Prometheus metric types
  • Registration helpers: Methods to convert metrics into Prometheus collectors
  • github.com/nabbar/golib/prometheus/metrics: Concrete metric implementations
  • github.com/nabbar/golib/prometheus/pool: Metric pool management
  • github.com/nabbar/golib/prometheus/webmetrics: Pre-configured web server metrics

Example Usage

This package is typically used indirectly through higher-level packages:

import (
    "github.com/nabbar/golib/prometheus/metrics"
    "github.com/nabbar/golib/prometheus/types"
)

// Create a metric using the types
metric := metrics.NewMetrics("my_counter", types.Counter)
metric.SetDesc("Example counter metric")

// The metric type determines how it's registered with Prometheus
collector, err := metric.GetType().Register(metric)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Metric

type Metric interface {
	// GetName returns the metric name.
	//
	// The name must follow Prometheus naming conventions:
	//   - Use snake_case (e.g., "http_request_duration_seconds")
	//   - Use base units (seconds, bytes, not milliseconds or megabytes)
	//   - Include unit suffix where applicable (_seconds, _bytes, _total)
	//   - Must be unique within a Prometheus registry
	//
	// Example: "http_requests_total", "process_cpu_seconds_total"
	GetName() string

	// GetType returns the Prometheus metric type.
	//
	// Supported types:
	//   - Counter: Monotonically increasing value (e.g., request count)
	//   - Gauge: Value that can go up or down (e.g., memory usage)
	//   - Histogram: Distribution of values with buckets (e.g., request duration)
	//   - Summary: Distribution with configurable quantiles (e.g., response size)
	//
	// The type determines how Prometheus stores and queries the metric.
	GetType() MetricType

	// GetDesc returns the metric description.
	//
	// The description should:
	//   - Be human-readable and concise
	//   - Explain what the metric measures
	//   - Include units if not in the metric name
	//   - Be suitable for display in Prometheus UI and Grafana
	//
	// Example: "Total number of HTTP requests", "Current memory usage in bytes"
	GetDesc() string

	// GetLabel returns the list of label names for this metric.
	//
	// Labels provide dimensional data for filtering and grouping:
	//   - Each label name becomes a dimension in Prometheus
	//   - Label values are provided during metric collection
	//   - Use labels for bounded cardinality (avoid user IDs, timestamps)
	//
	// Returns an empty slice if the metric has no labels.
	//
	// Example: []string{"method", "status"} for HTTP metrics
	//
	// Warning: High cardinality (many unique label combinations) can impact
	// Prometheus performance. Keep label value sets bounded.
	GetLabel() []string

	// GetBuckets returns the histogram bucket boundaries.
	//
	// Required only for Histogram metrics. Buckets define the ranges for
	// grouping observations:
	//   - Each bucket counts observations less than or equal to its value
	//   - Buckets must be in ascending order
	//   - Common patterns: exponential, linear buckets
	//
	// Returns nil for non-histogram metrics.
	//
	// Example: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}
	// for duration in seconds.
	//
	// See prometheus.DefBuckets, prometheus.ExponentialBuckets, and
	// prometheus.LinearBuckets for bucket generation helpers.
	GetBuckets() []float64

	// GetObjectives returns the summary quantile objectives.
	//
	// Required only for Summary metrics. Objectives define which quantiles
	// to calculate and their allowed error:
	//   - Key: Quantile (0.5 = median, 0.95 = 95th percentile, 0.99 = 99th percentile)
	//   - Value: Allowed error (e.g., 0.01 = ±1%)
	//
	// Returns nil for non-summary metrics.
	//
	// Example: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}
	// means calculate p50 (±5%), p90 (±1%), and p99 (±0.1%).
	//
	// Note: Summaries are computationally more expensive than histograms and
	// cannot be aggregated across instances. Prefer histograms when possible.
	GetObjectives() map[float64]float64
}

Metric defines the interface that all Prometheus metrics must implement.

This interface provides the contract for metric implementations, ensuring they can provide all necessary information for registration with Prometheus and proper metric collection.

Metric Properties

Each metric must provide:

  • A unique name following Prometheus naming conventions
  • A type (Counter, Gauge, Histogram, or Summary)
  • A human-readable description
  • Optional labels for dimensional data
  • Type-specific configuration (buckets for histograms, objectives for summaries)

Implementation

This interface is implemented by github.com/nabbar/golib/prometheus/metrics.Metric. Users typically don't implement this interface directly but use the provided implementation.

Thread Safety

Implementations of this interface should be safe for concurrent use, as metrics are often accessed from multiple goroutines simultaneously.

Example

// Using a concrete implementation
metric := metrics.NewMetrics("http_requests_total", types.Counter)
metric.SetDesc("Total HTTP requests")
metric.AddLabel("method", "status")

// Access via interface
var m types.Metric = metric
fmt.Println(m.GetName())   // "http_requests_total"
fmt.Println(m.GetType())   // types.Counter

type MetricType

type MetricType int

MetricType represents the type of a Prometheus metric.

Prometheus supports four fundamental metric types, each designed for specific use cases. The type determines how the metric is stored, aggregated, and queried.

Metric Types

Counter: For cumulative values that only increase (or reset to zero)

  • Use for: request counts, error counts, bytes transferred
  • Operations: increment, add
  • PromQL: rate(), increase(), irate()

Gauge: For values that can go up or down

  • Use for: memory usage, active connections, queue size, temperature
  • Operations: set, increment, decrement
  • PromQL: direct value, avg_over_time(), min_over_time(), max_over_time()

Histogram: For distributions with pre-defined buckets

  • Use for: request duration, response size
  • Provides: count, sum, and buckets
  • PromQL: histogram_quantile(), rate(<metric>_sum), rate(<metric>_count)
  • Pros: Aggregatable across instances, efficient
  • Cons: Fixed bucket boundaries

Summary: For distributions with streaming quantiles

  • Use for: request duration, response size (when histogram doesn't fit)
  • Provides: count, sum, and quantiles
  • PromQL: direct quantile values from <metric>{quantile="0.X"}
  • Pros: Accurate quantiles
  • Cons: Cannot aggregate across instances, computationally expensive

Choosing a Type

Use Counter when:

  • Value only increases (requests, errors, bytes sent)
  • You want to calculate rates

Use Gauge when:

  • Value can increase or decrease (memory, connections, queue depth)
  • You want current value or averages

Use Histogram when:

  • You need percentiles (p50, p95, p99)
  • You can define buckets upfront
  • You need to aggregate across multiple instances
  • Performance matters

Use Summary when:

  • You need precise quantiles
  • You cannot define buckets upfront
  • You don't need cross-instance aggregation

Example

// Counter for HTTP requests
requestCounter := metrics.NewMetrics("http_requests_total", types.Counter)

// Gauge for active connections
activaConns := metrics.NewMetrics("active_connections", types.Gauge)

// Histogram for request duration
latency := metrics.NewMetrics("request_duration_seconds", types.Histogram)
latency.AddBuckets(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)

// Summary for response size
size := metrics.NewMetrics("response_size_bytes", types.Summary)
size.SetObjectives(map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001})
const (
	// None represents an uninitialized or invalid metric type.
	//
	// This value should not be used for actual metrics. It exists as a zero value
	// for the MetricType enum and can be used to detect uninitialized metrics.
	//
	// Any attempt to register a metric with type None will fail.
	None MetricType = iota

	// Counter represents a cumulative metric that only increases.
	//
	// A counter is a monotonically increasing value that starts at zero and can only
	// increase (or be reset to zero on restart). Counters are ideal for tracking
	// cumulative counts of events.
	//
	// Common uses:
	//   - Total number of HTTP requests
	//   - Total number of errors
	//   - Total bytes transferred
	//   - Total number of tasks processed
	//
	// Operations:
	//   - Inc(): Increment by 1
	//   - Add(n): Increment by n (n must be positive)
	//
	// PromQL patterns:
	//   - rate(metric[5m]): Requests per second
	//   - increase(metric[1h]): Total increase over 1 hour
	//   - irate(metric[5m]): Instantaneous rate
	//
	// Example:
	//   http_requests_total{method="GET",status="200"} 12345
	Counter

	// Gauge represents a metric that can arbitrarily go up or down.
	//
	// A gauge represents a single numerical value that can increase or decrease.
	// Gauges are typically used for measured values that can fluctuate.
	//
	// Common uses:
	//   - Current memory usage
	//   - Number of active connections
	//   - Queue depth
	//   - Temperature readings
	//   - CPU usage percentage
	//
	// Operations:
	//   - Set(v): Set to specific value
	//   - Inc(): Increment by 1
	//   - Dec(): Decrement by 1
	//   - Add(v): Add v (can be negative)
	//   - Sub(v): Subtract v
	//
	// PromQL patterns:
	//   - metric: Current value
	//   - avg_over_time(metric[5m]): Average value
	//   - max_over_time(metric[1h]): Maximum value
	//   - min_over_time(metric[1h]): Minimum value
	//
	// Example:
	//   active_connections{server="web-1"} 42
	Gauge

	// Histogram represents a distribution of values with predefined buckets.
	//
	// A histogram samples observations (usually request durations or response sizes)
	// and counts them in configurable buckets. It also provides a sum of all observed
	// values and a total count.
	//
	// Metrics generated:
	//   - <name>_bucket{le="X"}: Cumulative count of observations <= X
	//   - <name>_sum: Sum of all observed values
	//   - <name>_count: Total number of observations
	//
	// Common uses:
	//   - HTTP request duration
	//   - Response size distribution
	//   - Query execution time
	//   - Job processing duration
	//
	// Operations:
	//   - Observe(v): Record an observation
	//
	// PromQL patterns:
	//   - histogram_quantile(0.95, rate(metric_bucket[5m])): 95th percentile
	//   - rate(metric_sum[5m]) / rate(metric_count[5m]): Average value
	//   - rate(metric_count[5m]): Operations per second
	//
	// Bucket configuration:
	//   Buckets must be defined when creating the metric:
	//   metric.AddBuckets(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)
	//
	// Advantages:
	//   - Can calculate quantiles across multiple instances
	//   - Efficient storage and computation
	//   - Aggregatable
	//
	// Example:
	//   http_request_duration_seconds_bucket{le="0.1"} 95000
	//   http_request_duration_seconds_bucket{le="0.5"} 99500
	//   http_request_duration_seconds_bucket{le="+Inf"} 100000
	//   http_request_duration_seconds_sum 28000
	//   http_request_duration_seconds_count 100000
	Histogram

	// Summary represents a distribution with streaming quantiles.
	//
	// A summary samples observations and calculates configurable quantiles over
	// a sliding time window. It's similar to a histogram but computes quantiles
	// on the client side.
	//
	// Metrics generated:
	//   - <name>{quantile="X"}: Pre-calculated quantile value
	//   - <name>_sum: Sum of all observed values
	//   - <name>_count: Total number of observations
	//
	// Common uses:
	//   - Request latencies (when precise quantiles needed)
	//   - Response sizes (when bucket ranges unknown)
	//
	// Operations:
	//   - Observe(v): Record an observation
	//
	// PromQL patterns:
	//   - metric{quantile="0.95"}: Pre-calculated 95th percentile
	//   - rate(metric_sum[5m]) / rate(metric_count[5m]): Average value
	//
	// Objectives configuration:
	//   Quantiles and their error margins must be defined:
	//   metric.SetObjectives(map[float64]float64{
	//       0.5: 0.05,   // median with ±5% error
	//       0.9: 0.01,   // 90th percentile with ±1% error
	//       0.99: 0.001, // 99th percentile with ±0.1% error
	//   })
	//
	// Disadvantages:
	//   - Cannot aggregate quantiles across instances
	//   - More computationally expensive than histograms
	//   - Quantiles are calculated per instance
	//
	// Recommendation:
	//   Prefer Histogram over Summary in most cases. Use Summary only when:
	//     - You cannot define buckets upfront
	//     - You need very precise quantiles for a single instance
	//     - Cross-instance aggregation is not needed
	//
	// Example:
	//   http_request_duration_seconds{quantile="0.5"} 0.15
	//   http_request_duration_seconds{quantile="0.9"} 0.35
	//   http_request_duration_seconds{quantile="0.99"} 0.75
	//   http_request_duration_seconds_sum 28000
	//   http_request_duration_seconds_count 100000
	Summary
)

func (MetricType) Register

func (m MetricType) Register(met Metric) (prmsdk.Collector, error)

Register converts a Metric into a Prometheus Collector.

This method creates the appropriate Prometheus collector (CounterVec, GaugeVec, HistogramVec, or SummaryVec) based on the metric's type. The collector can then be registered with a Prometheus registry.

Type-Specific Behavior

Counter:

  • Creates a CounterVec with the metric's name, description, and labels
  • No additional configuration required

Gauge:

  • Creates a GaugeVec with the metric's name, description, and labels
  • No additional configuration required

Histogram:

  • Creates a HistogramVec with buckets from GetBuckets()
  • Returns error if buckets are not configured
  • Error message: "metric 'X' is histogram type, cannot lose bucket param"

Summary:

  • Creates a SummaryVec with objectives from GetObjectives()
  • Returns error if objectives are not configured
  • Error message: "metric 'X' is summary type, cannot lose objectives param"

None:

  • Returns error: "metric type is not compatible"

Parameters

  • met: The metric to register. Must provide name, description, labels, and type-specific configuration (buckets for histogram, objectives for summary)

Returns

  • prmsdk.Collector: The created Prometheus collector, ready for registration
  • error: Non-nil if the metric type is invalid or required configuration is missing

Example

// Create and register a histogram
metric := metrics.NewMetrics("http_request_duration_seconds", types.Histogram)
metric.SetDesc("HTTP request latency")
metric.AddLabel("method", "status")
metric.AddBuckets(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)

collector, err := metric.GetType().Register(metric)
if err != nil {
    log.Fatal(err)
}

prometheus.MustRegister(collector)

Common Errors

  • "metric type is not compatible": Metric type is None or invalid
  • "cannot lose bucket param": Histogram metric has no buckets configured
  • "cannot lose objectives param": Summary metric has no objectives configured

Thread Safety

This method is safe to call concurrently. The returned collector is also thread-safe and can be used from multiple goroutines.

Jump to

Keyboard shortcuts

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