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 ¶
- func HTTPMiddleware(namespace string) func(http.Handler) http.Handler
- func Init(cfg MetricsConfig) error
- func InitStandardMetrics(namespace string) error
- func IsInitialized() bool
- func Registry() *prometheus.Registry
- func Shutdown(ctx context.Context) error
- func StreamServerInterceptor(namespace string) grpc.StreamServerInterceptor
- func UnaryServerInterceptor(namespace string) grpc.UnaryServerInterceptor
- type Counter
- type CounterOpts
- type Gauge
- func (g *Gauge) Add(value float64, labelValues ...string)
- func (g *Gauge) Dec(labelValues ...string)
- func (g *Gauge) Inc(labelValues ...string)
- func (g *Gauge) Set(value float64, labelValues ...string)
- func (g *Gauge) Sub(value float64, labelValues ...string)
- func (g *Gauge) WithLabelValues(labelValues ...string) prometheus.Gauge
- type GaugeOpts
- type Histogram
- type HistogramOpts
- type MetricsConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HTTPMiddleware ¶
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 ¶
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 ¶
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 ¶
Add increments the counter by the given value for the given label values. The value must be non-negative.
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 ¶
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) 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 ¶
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.