metrics

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package metrics provides Prometheus metrics middleware for celeris.

The middleware records per-request metrics (counters, histograms, gauges) and exposes them in Prometheus text exposition format at a configurable endpoint (default "/metrics").

Basic usage:

server.Use(metrics.New())

Custom configuration:

server.Use(metrics.New(metrics.Config{
    Path:      "/prom",
    Namespace: "myapp",
    Subsystem: "http",
    SkipPaths: []string{"/health", "/ready"},
}))

Security Warning

The metrics endpoint exposes internal server metrics. In production, protect it using Config.AuthFunc, a separate listener, authentication middleware, or network-level restriction.

Registered Metrics

  • {ns}_{sub}_requests_total (CounterVec): total HTTP requests
  • {ns}_{sub}_request_duration_seconds (HistogramVec): request latency
  • {ns}_{sub}_request_size_bytes (HistogramVec): request body size
  • {ns}_{sub}_response_size_bytes (HistogramVec): response body size
  • {ns}_{sub}_active_requests (Gauge): in-flight requests

The subsystem segment is omitted when Config.Subsystem is empty.

Custom Labels

Use Config.LabelFuncs to add custom label dimensions. Functions are called after c.Next() returns:

server.Use(metrics.New(metrics.Config{
    LabelFuncs: map[string]func(*celeris.Context) string{
        "region": func(c *celeris.Context) string {
            return c.Header("x-region")
        },
    },
}))

Cardinality Protection

Unmatched routes (404 with no registered pattern) use the sentinel path label "<unmatched>" to prevent high-cardinality label explosion.

Histogram Buckets

DefaultBuckets provides fine-grained latency boundaries:

[]float64{0.0005, 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 5}

Override with Config.Buckets for duration histograms or Config.SizeBuckets for request/response size histograms.

Registry Isolation

By default, the middleware creates a dedicated prometheus.Registry with Go runtime and process collectors. Pass a custom Config.Registry to use a shared or pre-configured registry.

Response Size and Compression

The response_size_bytes metric records c.BytesWritten() at the point metrics middleware runs in the chain. With the recommended ordering (metrics before compress), this records the uncompressed application-level size. If metrics runs after compress, it records the compressed network-level size. Be aware of this when interpreting response size dashboards.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultBuckets

func DefaultBuckets() []float64

DefaultBuckets returns the default histogram bucket boundaries for sub-millisecond latency resolution.

func New

func New(config ...Config) celeris.HandlerFunc

New creates a Prometheus metrics middleware with the given config.

Example
package main

import (
	"github.com/goceleris/celeris/middleware/metrics"
)

func main() {
	// Zero-config: registers metrics with a dedicated registry and
	// serves them at /metrics in Prometheus text format.
	_ = metrics.New()
}
Example (CustomPath)
package main

import (
	"github.com/goceleris/celeris/middleware/metrics"
)

func main() {
	// Serve metrics at a custom path with a custom namespace.
	_ = metrics.New(metrics.Config{
		Path:      "/prom",
		Namespace: "myapp",
		SkipPaths: []string{"/health", "/ready"},
	})
}
Example (CustomRegistry)
package main

import (
	"github.com/prometheus/client_golang/prometheus"

	"github.com/goceleris/celeris/middleware/metrics"
)

func main() {
	// Use a custom Prometheus registry for isolated metric collection.
	reg := prometheus.NewRegistry()
	_ = metrics.New(metrics.Config{
		Registry:  reg,
		Namespace: "gateway",
		Subsystem: "http",
	})
}

Types

type Config

type Config struct {
	// Skip defines a function to skip this middleware for certain requests.
	Skip func(c *celeris.Context) bool

	// SkipPaths lists paths to skip from metrics recording (exact match).
	// The metrics endpoint itself is never recorded regardless of this list.
	SkipPaths []string

	// Path is the HTTP path that serves the Prometheus metrics endpoint.
	// Default: "/metrics".
	Path string

	// Namespace is the Prometheus metric namespace prefix.
	// Default: "celeris".
	Namespace string

	// Subsystem is the Prometheus metric subsystem prefix.
	// Default: "" (no subsystem).
	Subsystem string

	// Buckets defines the histogram bucket boundaries for request duration.
	// Default: DefaultBuckets.
	Buckets []float64

	// Registry is the Prometheus registry to use for metric registration and
	// gathering. When nil, the middleware creates a dedicated registry with
	// Go runtime and process collectors pre-registered.
	Registry *prometheus.Registry

	// ConstLabels are applied to every metric registration as constant labels
	// (e.g., service name, environment).
	ConstLabels map[string]string

	// AuthFunc is an authentication check executed before serving the metrics
	// endpoint. If it returns false, the middleware responds with 403 Forbidden.
	// Default: nil (no auth, all requests to the metrics endpoint are served).
	AuthFunc func(c *celeris.Context) bool

	// IgnoreStatusCodes excludes requests with matching response status codes
	// from all metric recording (counter, histograms). Common use:
	// IgnoreStatusCodes: []int{404} to suppress scanner noise.
	IgnoreStatusCodes []int

	// LabelFuncs defines custom label dimensions appended to all metric
	// label sets. Each map key becomes a label name and the function extracts
	// the label value from the request context. The functions are called
	// after c.Next() returns, so response-derived values are available.
	LabelFuncs map[string]func(*celeris.Context) string

	// SizeBuckets defines histogram bucket boundaries for request and
	// response size histograms. Defaults to exponential byte-size buckets.
	SizeBuckets []float64
}

Config defines the metrics middleware configuration.

Jump to

Keyboard shortcuts

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