metrics

package module
v1.1.0 Latest Latest
Warning

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

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

README

metrics-kit

Go Reference Go Report Card License codecov

中文文档

A unified Prometheus metrics toolkit for Go services. This package provides metric builders, registry management, HTTP handlers, and middleware for consistent metrics collection across services.

Features

  • Registry Management: Custom Prometheus registry with namespace/subsystem support
  • Fluent Builders: Counter, Gauge, Histogram, and Summary builders with method chaining
  • HTTP Handlers: Standard and Fiber-compatible /metrics endpoint handlers (optional timeout via HandlerOpts)
  • HTTP Middleware: Request metrics collection for Fiber framework, with default path normalization to limit label cardinality
  • Label Safety: SanitizeLabelValue for safe label values from untrusted input; DefaultPathNormalize for path-based labels
  • Common Metrics: Pre-built metric patterns for cache, rate limiting, Redis, auth, OTP, etc.
  • Bucket Presets: Predefined histogram buckets for HTTP, Redis, external APIs, and bytes

Installation

go get github.com/soulteary/metrics-kit

Usage

Basic Registry and Counter
import (
    metrics "github.com/soulteary/metrics-kit"
)

// Create a registry with namespace
registry := metrics.NewRegistry("myservice")

// Build a counter with labels
requestsTotal := registry.Counter("requests_total").
    Help("Total number of requests").
    Labels("method", "status").
    BuildVec()

// Use the counter
requestsTotal.WithLabelValues("GET", "200").Inc()
requestsTotal.WithLabelValues("POST", "201").Add(5)
Histogram with Custom Buckets
// Build a histogram with custom buckets
latency := registry.Histogram("request_duration_seconds").
    Help("Request duration in seconds").
    Labels("endpoint").
    Buckets(metrics.HTTPDurationBuckets()).
    BuildVec()

// Record observations
latency.WithLabelValues("/api/users").Observe(0.125)
Gauge
// Build a gauge for tracking active connections
activeConns := registry.Gauge("active_connections").
    Help("Number of active connections").
    Build()

activeConns.Set(42)
activeConns.Inc()
activeConns.Dec()
HTTP Handler
import (
    "net/http"
    metrics "github.com/soulteary/metrics-kit"
)

// Standard library (uses default Prometheus registry only)
http.Handle("/metrics", metrics.Handler())

// With custom registry: use HandlerFor or NewHandler so your app's metrics are exposed
http.Handle("/metrics", metrics.HandlerFor(registry))

// For Fiber
app.Get("/metrics", metrics.FiberHandler())
app.Get("/metrics", metrics.FiberHandlerFor(registry)) // when using custom registry

// With options (e.g. custom registry + scrape timeout in seconds)
handler := metrics.NewHandler(metrics.HandlerOpts{
    Registry:          registry,
    EnableOpenMetrics: true,
    Timeout:           10,
})
http.Handle("/metrics", handler)
HTTP Middleware (Fiber)
import (
    "github.com/gofiber/fiber/v2"
    metrics "github.com/soulteary/metrics-kit"
)

app := fiber.New()

// Simple middleware
app.Use(metrics.NewFiberMiddleware("myservice"))

// With custom configuration (default config already uses DefaultPathNormalize)
cfg := metrics.HTTPMetricsConfig{
    Namespace:               "myservice",
    Subsystem:               "api",
    SkipPaths:               []string{"/health", "/metrics"},
    IncludeRequestSize:      true,
    IncludeResponseSize:     true,
    IncludeRequestsInFlight: true,
    PathTransformFunc:       metrics.DefaultPathNormalize, // /users/123 -> /users/:id
}
app.Use(metrics.NewFiberMiddlewareWithConfig(cfg))
Common Metrics Patterns
registry := metrics.NewRegistry("myservice")
cm := metrics.NewCommonMetrics(registry)

// Cache metrics
cache := cm.NewCacheMetrics("users")
cache.RecordHit()
cache.RecordMiss()
cache.SetSize(100)

// Rate limit metrics
rateLimit := cm.NewRateLimitMetrics()
rateLimit.RecordHit("user")
rateLimit.RecordHit("ip")

// Redis metrics
redis := cm.NewRedisMetrics()
redis.RecordSuccess("get", 5*time.Millisecond)
redis.RecordFailure("set", 100*time.Millisecond)
redis.SetActiveConnections(10)

// External service metrics (e.g., Warden, Herald)
warden := cm.NewExternalServiceMetrics("warden")
warden.RecordSuccess("check_user", 50*time.Millisecond)
warden.RecordFailure("get_info", 200*time.Millisecond)

// Background task metrics
tasks := cm.NewBackgroundTaskMetrics()
tasks.IncRunning()
tasks.RecordSuccess("sync", 5*time.Second)
tasks.DecRunning()

// Auth metrics
auth := cm.NewAuthMetrics()
auth.RecordSuccess("password")
auth.RecordSessionCreated()

// OTP metrics
otp := cm.NewOTPMetrics()
otp.RecordChallengeCreated("email", "login", "success")
otp.RecordSend("email", "smtp", "success", 100*time.Millisecond)
otp.RecordVerification("success", "")
Bucket Presets
// HTTP request duration buckets
// 1ms, 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s, 5s, 10s
metrics.HTTPDurationBuckets()

// Redis operation duration buckets
// 0.5ms, 1ms, 2.5ms, 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s
metrics.RedisDurationBuckets()

// External API call duration buckets
// 10ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s, 5s, 10s, 30s
metrics.ExternalAPIDurationBuckets()

// Request/response size buckets
// 100B, 1KB, 10KB, 100KB, 1MB, 10MB
metrics.BytesBuckets()

// Default Prometheus buckets
metrics.DefaultBuckets()

Project Structure

metrics-kit/
├── registry.go       # Registry management with namespace/subsystem
├── builders.go       # Fluent metric builders (Counter, Histogram, Gauge, Summary)
├── labels.go         # Label safety: SanitizeLabelValue, DefaultPathNormalize
├── http.go           # HTTP handlers for /metrics endpoint
├── middleware.go     # Fiber HTTP middleware
├── common.go         # Common metric patterns (cache, redis, auth, OTP, etc.)
└── *_test.go         # Comprehensive tests

Integration Example

Herald (OTP Service)
package main

import (
    "github.com/gofiber/fiber/v2"
    metrics "github.com/soulteary/metrics-kit"
)

func main() {
    registry := metrics.NewRegistry("herald")
    cm := metrics.NewCommonMetrics(registry)
    
    // Create OTP metrics
    otp := cm.NewOTPMetrics()
    redis := cm.NewRedisMetrics()
    rateLimit := cm.NewRateLimitMetrics()
    
    app := fiber.New()
    
    // Add metrics middleware
    app.Use(metrics.NewFiberMiddleware("herald"))
    
    // Add metrics endpoint
    app.Get("/metrics", metrics.FiberHandlerFor(registry))
    
    // Use metrics in handlers
    app.Post("/v1/otp/challenges", func(c *fiber.Ctx) error {
        // ... create challenge logic ...
        otp.RecordChallengeCreated("email", "login", "success")
        return c.JSON(response)
    })
    
    app.Listen(":8080")
}
Stargate (Auth Gateway)
package main

import (
    metrics "github.com/soulteary/metrics-kit"
)

func main() {
    registry := metrics.NewRegistry("stargate")
    cm := metrics.NewCommonMetrics(registry)
    
    auth := cm.NewAuthMetrics()
    heraldCalls := cm.NewExternalServiceMetrics("herald")
    wardenCalls := cm.NewExternalServiceMetrics("warden")
    
    // Use in auth flow
    auth.RecordSuccess("warden_otp")
    auth.RecordSessionCreated()
    
    // Track external service calls
    heraldCalls.RecordSuccess("create_challenge", 150*time.Millisecond)
    wardenCalls.RecordSuccess("check_user", 50*time.Millisecond)
}

Security and Deployment

  • Protect the /metrics endpoint. The handlers returned by Handler(), HandlerFor(), etc. do not perform authentication. Do not expose /metrics to the public internet. Prefer one or more of: a dedicated admin port, network policies, reverse-proxy authentication, or IP allowlisting so only your monitoring stack can scrape.
  • Path label cardinality. The default HTTP metrics config uses DefaultPathNormalize so paths like /users/123 become /users/:id. In production, always use path normalization (or skip certain paths) to avoid unbounded time series and potential DoS from high cardinality.
  • Label values from untrusted input. For metrics that use labels from user or external input (e.g. in CommonMetrics such as scope, operation, provider), either pass only controlled enum-like values or sanitize with SanitizeLabelValue(s, metrics.DefaultLabelValueMaxLength) to avoid breaking the exposition format (e.g. newlines in label values). Example: scope := metrics.SanitizeLabelValue(userInput, metrics.DefaultLabelValueMaxLength) before calling rateLimit.RecordHit(scope).

Registry and Unregister

  • Unregister(name) only affects collectors that were registered with Register(name, collector). Metrics created via the builders (Build() / BuildVec()) are registered with MustRegister and are not tracked by name; to remove them, keep the collector reference and call the underlying registry.PrometheusRegistry().Unregister(collector).

Requirements

  • Go 1.25 or later
  • github.com/prometheus/client_golang v1.22.0+
  • github.com/gofiber/fiber/v2 v2.52.6+ (for Fiber middleware)

Test Coverage

Run tests:

go test ./... -v

# With coverage
go test ./... -coverprofile=coverage.out -covermode=atomic
go tool cover -html=coverage.out -o coverage.html
go tool cover -func=coverage.out

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

See LICENSE file for details.

Documentation

Overview

Package metrics provides a unified Prometheus metrics toolkit for Go services. It includes registry management, metric builders, HTTP handlers, and middleware.

Index

Constants

View Source
const DefaultLabelValueMaxLength = 256

Default max length for a single label value to avoid unbounded cardinality and exposition bloat. Prometheus does not enforce a limit; this is a reasonable default for safety.

Variables

This section is empty.

Functions

func BytesBuckets

func BytesBuckets() []float64

BytesBuckets returns buckets suitable for request/response size tracking. Values: 100B, 1KB, 10KB, 100KB, 1MB, 10MB

func DefaultBuckets

func DefaultBuckets() []float64

DefaultBuckets returns the default Prometheus histogram buckets.

func DefaultPathNormalize added in v1.1.0

func DefaultPathNormalize(path string) string

DefaultPathNormalize normalizes request paths for use as metric labels to avoid cardinality explosion. It replaces numeric and UUID-like path segments with ":id", e.g. /users/123 -> /users/:id, /items/550e8400-e29b-41d4-a716-446655440000 -> /items/:id. Use this as PathTransformFunc in production so each distinct ID does not create a new time series.

func ExternalAPIDurationBuckets

func ExternalAPIDurationBuckets() []float64

ExternalAPIDurationBuckets returns buckets suitable for external API call duration tracking. Values: 10ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s, 5s, 10s, 30s

func FiberHandler

func FiberHandler() fiber.Handler

FiberHandler returns a Fiber-compatible handler for the /metrics endpoint using the default Prometheus registry.

func FiberHandlerFor

func FiberHandlerFor(registry *Registry) fiber.Handler

FiberHandlerFor returns a Fiber-compatible handler for the given registry.

func FiberHandlerForGatherer

func FiberHandlerForGatherer(gatherer prometheus.Gatherer) fiber.Handler

FiberHandlerForGatherer returns a Fiber-compatible handler for the given Gatherer.

func HTTPDurationBuckets

func HTTPDurationBuckets() []float64

HTTPDurationBuckets returns buckets suitable for HTTP request duration tracking. Values: 1ms, 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s, 5s, 10s

func Handler

func Handler() http.Handler

Handler returns a standard http.Handler for the /metrics endpoint using the default Prometheus registry.

func HandlerFor

func HandlerFor(registry *Registry) http.Handler

HandlerFor returns an http.Handler for the given registry.

func HandlerForGatherer

func HandlerForGatherer(gatherer prometheus.Gatherer) http.Handler

HandlerForGatherer returns an http.Handler for the given Gatherer.

func NewFiberHandler

func NewFiberHandler(opts HandlerOpts) fiber.Handler

NewFiberHandler creates a new Fiber metrics handler with the given options.

func NewFiberMiddleware

func NewFiberMiddleware(namespace string) fiber.Handler

NewFiberMiddleware creates a Fiber middleware with default configuration.

func NewFiberMiddlewareWithConfig

func NewFiberMiddlewareWithConfig(cfg HTTPMetricsConfig) fiber.Handler

NewFiberMiddlewareWithConfig creates a Fiber middleware with custom configuration.

func NewHandler

func NewHandler(opts HandlerOpts) http.Handler

NewHandler creates a new metrics HTTP handler with the given options. When Timeout is greater than 0, the handler is wrapped with http.TimeoutHandler; timed-out requests respond with 503 Service Unavailable.

func RedisDurationBuckets

func RedisDurationBuckets() []float64

RedisDurationBuckets returns buckets suitable for Redis operation duration tracking. Values: 0.5ms, 1ms, 2.5ms, 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s

func RegisterHTTPHandler

func RegisterHTTPHandler(mux *http.ServeMux, path string)

RegisterHTTPHandler registers the metrics handler on an http.ServeMux.

func RegisterHTTPHandlerFor

func RegisterHTTPHandlerFor(mux *http.ServeMux, path string, registry *Registry)

RegisterHTTPHandlerFor registers a metrics handler for the given registry.

func SanitizeLabelValue added in v1.1.0

func SanitizeLabelValue(s string, maxLen int) string

SanitizeLabelValue returns a value safe for use as a Prometheus label value. It replaces newlines and carriage returns (which would break the exposition format), escapes backslashes, and truncates to maxLen runes. Use 0 for maxLen to skip truncation. Call this for any label value that may come from untrusted input (e.g. request path, user-provided strings).

Types

type AuthMetrics

type AuthMetrics struct {
	RequestsTotal     *prometheus.CounterVec
	SessionsCreated   prometheus.Counter
	SessionsDestroyed prometheus.Counter
}

AuthMetrics holds authentication metrics.

func (*AuthMetrics) RecordAuthRequest

func (m *AuthMetrics) RecordAuthRequest(method, result string)

RecordAuthRequest records an authentication request.

func (*AuthMetrics) RecordFailure

func (m *AuthMetrics) RecordFailure(method string)

RecordFailure records a failed authentication.

func (*AuthMetrics) RecordSessionCreated

func (m *AuthMetrics) RecordSessionCreated()

RecordSessionCreated records a session creation.

func (*AuthMetrics) RecordSessionDestroyed

func (m *AuthMetrics) RecordSessionDestroyed()

RecordSessionDestroyed records a session destruction.

func (*AuthMetrics) RecordSuccess

func (m *AuthMetrics) RecordSuccess(method string)

RecordSuccess records a successful authentication.

type BackgroundTaskMetrics

type BackgroundTaskMetrics struct {
	ExecutionsTotal *prometheus.CounterVec
	Duration        *prometheus.HistogramVec
	ErrorsTotal     prometheus.Counter
	Running         prometheus.Gauge
}

BackgroundTaskMetrics holds metrics for background tasks.

func (*BackgroundTaskMetrics) DecRunning

func (m *BackgroundTaskMetrics) DecRunning()

DecRunning decrements the running task count.

func (*BackgroundTaskMetrics) IncRunning

func (m *BackgroundTaskMetrics) IncRunning()

IncRunning increments the running task count.

func (*BackgroundTaskMetrics) RecordExecution

func (m *BackgroundTaskMetrics) RecordExecution(task, result string, duration time.Duration)

RecordExecution records a background task execution.

func (*BackgroundTaskMetrics) RecordFailure

func (m *BackgroundTaskMetrics) RecordFailure(task string, duration time.Duration)

RecordFailure records a failed task execution.

func (*BackgroundTaskMetrics) RecordSuccess

func (m *BackgroundTaskMetrics) RecordSuccess(task string, duration time.Duration)

RecordSuccess records a successful task execution.

type CacheMetrics

type CacheMetrics struct {
	Hits   prometheus.Counter
	Misses prometheus.Counter
	Size   prometheus.Gauge
	Errors prometheus.Counter
}

CacheMetrics holds cache-related metrics.

func (*CacheMetrics) RecordError

func (m *CacheMetrics) RecordError()

RecordError records a cache error.

func (*CacheMetrics) RecordHit

func (m *CacheMetrics) RecordHit()

RecordHit records a cache hit.

func (*CacheMetrics) RecordMiss

func (m *CacheMetrics) RecordMiss()

RecordMiss records a cache miss.

func (*CacheMetrics) SetSize

func (m *CacheMetrics) SetSize(size float64)

SetSize sets the current cache size.

type CommonMetrics

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

CommonMetrics provides frequently used metric patterns for services.

func NewCommonMetrics

func NewCommonMetrics(registry *Registry) *CommonMetrics

NewCommonMetrics creates a new CommonMetrics instance.

func (*CommonMetrics) NewAuthMetrics

func (cm *CommonMetrics) NewAuthMetrics() *AuthMetrics

NewAuthMetrics creates authentication metrics.

func (*CommonMetrics) NewBackgroundTaskMetrics

func (cm *CommonMetrics) NewBackgroundTaskMetrics() *BackgroundTaskMetrics

NewBackgroundTaskMetrics creates background task metrics.

func (*CommonMetrics) NewCacheMetrics

func (cm *CommonMetrics) NewCacheMetrics(name string) *CacheMetrics

NewCacheMetrics creates cache metrics with the given name prefix.

func (*CommonMetrics) NewExternalServiceMetrics

func (cm *CommonMetrics) NewExternalServiceMetrics(serviceName string) *ExternalServiceMetrics

NewExternalServiceMetrics creates metrics for an external service.

func (*CommonMetrics) NewOTPMetrics

func (cm *CommonMetrics) NewOTPMetrics() *OTPMetrics

NewOTPMetrics creates OTP metrics.

func (*CommonMetrics) NewRateLimitMetrics

func (cm *CommonMetrics) NewRateLimitMetrics() *RateLimitMetrics

NewRateLimitMetrics creates rate limit metrics.

func (*CommonMetrics) NewRedisMetrics

func (cm *CommonMetrics) NewRedisMetrics() *RedisMetrics

NewRedisMetrics creates Redis operation metrics.

type CounterBuilder

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

CounterBuilder provides a fluent interface for building Counter metrics.

func (*CounterBuilder) Build

func (b *CounterBuilder) Build() prometheus.Counter

Build creates and registers a Counter (without labels).

func (*CounterBuilder) BuildVec

func (b *CounterBuilder) BuildVec() *prometheus.CounterVec

BuildVec creates and registers a CounterVec (with labels).

func (*CounterBuilder) ConstLabels

func (b *CounterBuilder) ConstLabels(labels prometheus.Labels) *CounterBuilder

ConstLabels sets constant labels for the counter.

func (*CounterBuilder) Help

func (b *CounterBuilder) Help(help string) *CounterBuilder

Help sets the help text for the counter.

func (*CounterBuilder) Labels

func (b *CounterBuilder) Labels(labels ...string) *CounterBuilder

Labels sets the label names for the counter.

type ExternalServiceMetrics

type ExternalServiceMetrics struct {
	CallsTotal   *prometheus.CounterVec
	CallDuration *prometheus.HistogramVec
}

ExternalServiceMetrics holds metrics for external service calls.

func (*ExternalServiceMetrics) RecordCall

func (m *ExternalServiceMetrics) RecordCall(operation, result string, duration time.Duration)

RecordCall records an external service call.

func (*ExternalServiceMetrics) RecordFailure

func (m *ExternalServiceMetrics) RecordFailure(operation string, duration time.Duration)

RecordFailure records a failed external service call.

func (*ExternalServiceMetrics) RecordSuccess

func (m *ExternalServiceMetrics) RecordSuccess(operation string, duration time.Duration)

RecordSuccess records a successful external service call.

type GaugeBuilder

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

GaugeBuilder provides a fluent interface for building Gauge metrics.

func (*GaugeBuilder) Build

func (b *GaugeBuilder) Build() prometheus.Gauge

Build creates and registers a Gauge (without labels).

func (*GaugeBuilder) BuildVec

func (b *GaugeBuilder) BuildVec() *prometheus.GaugeVec

BuildVec creates and registers a GaugeVec (with labels).

func (*GaugeBuilder) ConstLabels

func (b *GaugeBuilder) ConstLabels(labels prometheus.Labels) *GaugeBuilder

ConstLabels sets constant labels for the gauge.

func (*GaugeBuilder) Help

func (b *GaugeBuilder) Help(help string) *GaugeBuilder

Help sets the help text for the gauge.

func (*GaugeBuilder) Labels

func (b *GaugeBuilder) Labels(labels ...string) *GaugeBuilder

Labels sets the label names for the gauge.

type HTTPMetrics

type HTTPMetrics struct {
	// RequestsTotal counts total HTTP requests by method, path, and status
	RequestsTotal *prometheus.CounterVec

	// RequestDuration observes request latency by method and path
	RequestDuration *prometheus.HistogramVec

	// RequestsInFlight tracks currently processing requests
	RequestsInFlight prometheus.Gauge

	// RequestSize observes request body size
	RequestSize *prometheus.HistogramVec

	// ResponseSize observes response body size
	ResponseSize *prometheus.HistogramVec
}

HTTPMetrics holds the metrics collectors for HTTP request monitoring.

func NewHTTPMetrics

func NewHTTPMetrics(cfg HTTPMetricsConfig) *HTTPMetrics

NewHTTPMetrics creates a new HTTPMetrics with the given configuration.

func (*HTTPMetrics) FiberMiddleware

func (m *HTTPMetrics) FiberMiddleware(cfg HTTPMetricsConfig) fiber.Handler

FiberMiddleware returns a Fiber middleware that collects HTTP metrics.

func (*HTTPMetrics) RecordRequest

func (m *HTTPMetrics) RecordRequest(method, path, status string, duration time.Duration)

RecordRequest records a single HTTP request metric. This is useful for manual metric recording outside of middleware. Method, path, and status are sanitized for safe use as label values.

func (*HTTPMetrics) RecordRequestWithSize

func (m *HTTPMetrics) RecordRequestWithSize(method, path, status string, duration time.Duration, reqSize, respSize int)

RecordRequestWithSize records an HTTP request with size information.

type HTTPMetricsConfig

type HTTPMetricsConfig struct {
	// Registry is the metrics registry to use. If nil, creates a new one.
	Registry *Registry

	// Namespace for metrics (e.g., "myservice")
	Namespace string

	// Subsystem for metrics (default: "http")
	Subsystem string

	// DurationBuckets for the request duration histogram
	DurationBuckets []float64

	// SizeBuckets for request/response size histograms
	SizeBuckets []float64

	// SkipPaths is a list of paths to skip metrics collection
	SkipPaths []string

	// PathTransformFunc transforms the request path before using it as a label.
	// This is useful for normalizing paths with parameters (e.g., /users/123 -> /users/:id)
	PathTransformFunc func(path string) string

	// IncludeRequestSize enables request size tracking
	IncludeRequestSize bool

	// IncludeResponseSize enables response size tracking
	IncludeResponseSize bool

	// IncludeRequestsInFlight enables in-flight request tracking
	IncludeRequestsInFlight bool
}

HTTPMetricsConfig configures the HTTP metrics middleware.

func DefaultHTTPMetricsConfig

func DefaultHTTPMetricsConfig() HTTPMetricsConfig

DefaultHTTPMetricsConfig returns the default configuration for HTTP metrics. PathTransformFunc is set to DefaultPathNormalize to avoid label cardinality explosion in production; override to nil or a custom function if you need raw paths or different normalization.

type HandlerOpts

type HandlerOpts struct {
	// Registry is the custom registry to use. If nil, uses default registry.
	Registry *Registry

	// ErrorHandling defines how errors are handled.
	// See promhttp.HandlerOpts for details.
	ErrorHandling promhttp.HandlerErrorHandling

	// ErrorLog is an optional logger for errors.
	ErrorLog promhttp.Logger

	// EnableOpenMetrics enables OpenMetrics format in addition to standard format.
	EnableOpenMetrics bool

	// DisableCompression disables response compression.
	DisableCompression bool

	// MaxRequestsInFlight limits concurrent requests. 0 means no limit.
	MaxRequestsInFlight int

	// Timeout specifies the maximum time for a request in seconds.
	// When > 0, the handler is wrapped with http.TimeoutHandler; 0 means no timeout.
	Timeout int
}

HandlerOpts provides options for configuring metrics handlers.

func DefaultHandlerOpts

func DefaultHandlerOpts() HandlerOpts

DefaultHandlerOpts returns the default handler options.

type HistogramBuilder

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

HistogramBuilder provides a fluent interface for building Histogram metrics.

func (*HistogramBuilder) Buckets

func (b *HistogramBuilder) Buckets(buckets []float64) *HistogramBuilder

Buckets sets the bucket boundaries for the histogram.

func (*HistogramBuilder) Build

Build creates and registers a Histogram (without labels).

func (*HistogramBuilder) BuildVec

func (b *HistogramBuilder) BuildVec() *prometheus.HistogramVec

BuildVec creates and registers a HistogramVec (with labels).

func (*HistogramBuilder) ConstLabels

func (b *HistogramBuilder) ConstLabels(labels prometheus.Labels) *HistogramBuilder

ConstLabels sets constant labels for the histogram.

func (*HistogramBuilder) Help

func (b *HistogramBuilder) Help(help string) *HistogramBuilder

Help sets the help text for the histogram.

func (*HistogramBuilder) Labels

func (b *HistogramBuilder) Labels(labels ...string) *HistogramBuilder

Labels sets the label names for the histogram.

type OTPMetrics

type OTPMetrics struct {
	ChallengesTotal    *prometheus.CounterVec
	SendsTotal         *prometheus.CounterVec
	SendDuration       *prometheus.HistogramVec
	VerificationsTotal *prometheus.CounterVec
}

OTPMetrics holds OTP/verification code metrics.

func (*OTPMetrics) RecordChallengeCreated

func (m *OTPMetrics) RecordChallengeCreated(channel, purpose, result string)

RecordChallengeCreated records a challenge creation event.

func (*OTPMetrics) RecordSend

func (m *OTPMetrics) RecordSend(channel, provider, result string, duration time.Duration)

RecordSend records an OTP send event.

func (*OTPMetrics) RecordVerification

func (m *OTPMetrics) RecordVerification(result, reason string)

RecordVerification records a verification event.

type RateLimitMetrics

type RateLimitMetrics struct {
	Hits *prometheus.CounterVec
}

RateLimitMetrics holds rate limiting metrics.

func (*RateLimitMetrics) RecordHit

func (m *RateLimitMetrics) RecordHit(scope string)

RecordHit records a rate limit hit for the given scope. Common scopes: "user", "ip", "destination", "resend_cooldown"

type RedisMetrics

type RedisMetrics struct {
	OperationsTotal   *prometheus.CounterVec
	OperationDuration *prometheus.HistogramVec
	ConnectionsActive prometheus.Gauge
	ConnectionErrors  prometheus.Counter
}

RedisMetrics holds Redis operation metrics.

func (*RedisMetrics) RecordConnectionError

func (m *RedisMetrics) RecordConnectionError()

RecordConnectionError records a connection error.

func (*RedisMetrics) RecordFailure

func (m *RedisMetrics) RecordFailure(operation string, duration time.Duration)

RecordFailure records a failed Redis operation.

func (*RedisMetrics) RecordOperation

func (m *RedisMetrics) RecordOperation(operation, result string, duration time.Duration)

RecordOperation records a Redis operation.

func (*RedisMetrics) RecordSuccess

func (m *RedisMetrics) RecordSuccess(operation string, duration time.Duration)

RecordSuccess records a successful Redis operation.

func (*RedisMetrics) SetActiveConnections

func (m *RedisMetrics) SetActiveConnections(count float64)

SetActiveConnections sets the number of active connections.

type Registry

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

Registry wraps prometheus.Registry with additional functionality for managing metrics in a service-oriented way.

func DefaultRegistry

func DefaultRegistry() *Registry

DefaultRegistry returns a Registry wrapping the default Prometheus registry.

func NewRegistry

func NewRegistry(namespace string) *Registry

NewRegistry creates a new Registry with the given namespace. The namespace is typically the service name (e.g., "herald", "stargate").

func NewRegistryWithSubsystem

func NewRegistryWithSubsystem(namespace, subsystem string) *Registry

NewRegistryWithSubsystem creates a new Registry with namespace and subsystem.

func (*Registry) Counter

func (r *Registry) Counter(name string) *CounterBuilder

Counter creates a new CounterBuilder.

func (*Registry) Gatherer

func (r *Registry) Gatherer() prometheus.Gatherer

Gatherer returns the underlying prometheus.Gatherer interface.

func (*Registry) Gauge

func (r *Registry) Gauge(name string) *GaugeBuilder

Gauge creates a new GaugeBuilder.

func (*Registry) Histogram

func (r *Registry) Histogram(name string) *HistogramBuilder

Histogram creates a new HistogramBuilder.

func (*Registry) MustRegister

func (r *Registry) MustRegister(collectors ...prometheus.Collector)

MustRegister registers collectors and panics on error.

func (*Registry) Namespace

func (r *Registry) Namespace() string

Namespace returns the registry's namespace.

func (*Registry) PrometheusRegistry

func (r *Registry) PrometheusRegistry() *prometheus.Registry

PrometheusRegistry returns the underlying *prometheus.Registry.

func (*Registry) Register

func (r *Registry) Register(name string, collector prometheus.Collector) error

Register registers a collector with the registry. It tracks the collector for later unregistration.

func (*Registry) Registerer

func (r *Registry) Registerer() prometheus.Registerer

Registerer returns the underlying prometheus.Registerer interface.

func (*Registry) Subsystem

func (r *Registry) Subsystem() string

Subsystem returns the registry's subsystem.

func (*Registry) Summary

func (r *Registry) Summary(name string) *SummaryBuilder

Summary creates a new SummaryBuilder.

func (*Registry) Unregister

func (r *Registry) Unregister(name string) bool

Unregister removes a collector from the registry.

func (*Registry) WithSubsystem

func (r *Registry) WithSubsystem(subsystem string) *Registry

WithSubsystem returns a new Registry with the same underlying registry but a different subsystem.

type SummaryBuilder

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

SummaryBuilder provides a fluent interface for building Summary metrics.

func (*SummaryBuilder) Build

func (b *SummaryBuilder) Build() prometheus.Summary

Build creates and registers a Summary (without labels).

func (*SummaryBuilder) BuildVec

func (b *SummaryBuilder) BuildVec() *prometheus.SummaryVec

BuildVec creates and registers a SummaryVec (with labels).

func (*SummaryBuilder) ConstLabels

func (b *SummaryBuilder) ConstLabels(labels prometheus.Labels) *SummaryBuilder

ConstLabels sets constant labels for the summary.

func (*SummaryBuilder) Help

func (b *SummaryBuilder) Help(help string) *SummaryBuilder

Help sets the help text for the summary.

func (*SummaryBuilder) Labels

func (b *SummaryBuilder) Labels(labels ...string) *SummaryBuilder

Labels sets the label names for the summary.

func (*SummaryBuilder) Objectives

func (b *SummaryBuilder) Objectives(objectives map[float64]float64) *SummaryBuilder

Objectives sets the quantile objectives for the summary.

Jump to

Keyboard shortcuts

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