prometheus

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package prometheus provides Prometheus metrics integration bundle for Forge applications.

The Prometheus bundle provides:

  • Automatic application metrics (HTTP requests, gRPC calls, errors)
  • Custom metrics registration and collection
  • Integration with existing framework components
  • Health check metrics and monitoring
  • Connection pool and database metrics
  • JWT authentication metrics
  • Circuit breaker and retry metrics
  • Grafana dashboard configuration

Basic Usage

Add the Prometheus bundle to your application:

config := prometheus.Config{
	Namespace: "myservice",
	Subsystem: "api",
	EnableDefaultMetrics: true,
	EnableHTTPMetrics: true,
	EnableGRPCMetrics: true,
}

bundle := prometheus.NewBundle(config)

app, err := framework.New(
	framework.WithConfig(&baseConfig),
	framework.WithBundle(bundle),
)

Custom Metrics

Register and use custom metrics:

// Get metrics registry
registry := bundle.Registry()

// Create custom counter
userCreated := prometheus.NewCounterVec(
	prometheus.CounterOpts{
		Namespace: "myservice",
		Name:      "users_created_total",
		Help:      "Total number of users created",
	},
	[]string{"source"},
)
registry.MustRegister(userCreated)

// Use in your code
userCreated.WithLabelValues("api").Inc()

Automatic Metrics

The bundle automatically collects:

  • HTTP request metrics (duration, count, status codes)
  • gRPC call metrics (duration, count, status codes)
  • Health check metrics (success/failure, duration)
  • Database connection pool metrics
  • Redis connection pool metrics
  • JWT authentication metrics
  • Circuit breaker state metrics

Integration with Other Bundles

The Prometheus bundle automatically integrates with:

  • PostgreSQL bundle for database metrics
  • Redis bundle for cache and connection metrics
  • JWT bundle for authentication metrics
  • HTTP client bundle for request metrics

Grafana Integration

The bundle provides pre-built Grafana dashboards for:

  • Application overview and health
  • HTTP and gRPC request monitoring
  • Database and cache performance
  • Error rates and SLA monitoring

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bundle

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

Bundle provides Prometheus metrics integration for Forge applications.

func NewBundle

func NewBundle(config Config) *Bundle

NewBundle creates a new Prometheus metrics bundle.

func (*Bundle) CollectConnectionMetrics

func (b *Bundle) CollectConnectionMetrics(ctx context.Context, app *framework.App)

CollectConnectionMetrics collects connection pool metrics from other bundles.

func (*Bundle) CreateCustomCounter

func (b *Bundle) CreateCustomCounter(name, help string, labelNames []string) (*prometheus.CounterVec, error)

CreateCustomCounter creates a new counter metric with consistent labeling and validation.

func (*Bundle) CreateCustomGauge

func (b *Bundle) CreateCustomGauge(name, help string, labelNames []string) (*prometheus.GaugeVec, error)

CreateCustomGauge creates a new gauge metric with consistent labeling and validation.

func (*Bundle) CreateCustomHistogram

func (b *Bundle) CreateCustomHistogram(name, help string, labelNames []string) (*prometheus.HistogramVec, error)

CreateCustomHistogram creates a new histogram metric with consistent labeling and validation.

func (*Bundle) CreateCustomSummary

func (b *Bundle) CreateCustomSummary(name, help string, labelNames []string, objectives map[float64]float64) (*prometheus.SummaryVec, error)

CreateCustomSummary creates a new summary metric with consistent labeling and validation.

func (*Bundle) Gatherer

func (b *Bundle) Gatherer() prometheus.Gatherer

Gatherer returns the Prometheus gatherer for metric collection.

func (*Bundle) GetMetricsHandler

func (b *Bundle) GetMetricsHandler() http.Handler

GetMetricsHandler returns an HTTP handler for the /metrics endpoint with basic security.

func (*Bundle) GetSecureMetricsHandler

func (b *Bundle) GetSecureMetricsHandler(secConfig SecurityConfig) http.Handler

GetSecureMetricsHandler returns a secured HTTP handler for the /metrics endpoint.

func (*Bundle) HealthChecks

func (b *Bundle) HealthChecks() []forgeHealth.Check

HealthChecks returns health checks for the Prometheus metrics system.

func (*Bundle) Initialize

func (b *Bundle) Initialize(app *framework.App) error

Initialize sets up Prometheus metrics collection.

func (*Bundle) Name

func (b *Bundle) Name() string

Name returns the bundle name.

func (*Bundle) RecordGRPCRequest

func (b *Bundle) RecordGRPCRequest(method, statusCode string, duration time.Duration)

RecordGRPCRequest records metrics for a gRPC request.

func (*Bundle) RecordHTTPRequest

func (b *Bundle) RecordHTTPRequest(method, endpoint string, statusCode int, duration time.Duration)

RecordHTTPRequest records metrics for an HTTP request.

func (*Bundle) RecordHealthCheck

func (b *Bundle) RecordHealthCheck(checkName, checkType string, success bool, duration time.Duration)

RecordHealthCheck records metrics for a health check.

func (*Bundle) RecordJWTValidation

func (b *Bundle) RecordJWTValidation(success bool, service string)

RecordJWTValidation records JWT token validation metrics.

func (*Bundle) Registry

func (b *Bundle) Registry() prometheus.Registerer

Registry returns the Prometheus registry for custom metric registration.

func (*Bundle) StartMetricsCollection

func (b *Bundle) StartMetricsCollection(ctx context.Context, collectors []MetricsCollector, interval time.Duration)

StartMetricsCollection starts periodic collection of metrics from registered collectors.

func (*Bundle) Stop

func (b *Bundle) Stop(ctx context.Context) error

Stop implements the Bundle interface for graceful shutdown. Prometheus bundle has no persistent resources requiring cleanup.

func (*Bundle) UpdateCircuitBreakerState

func (b *Bundle) UpdateCircuitBreakerState(name string, state int)

UpdateCircuitBreakerState updates circuit breaker state metrics.

func (*Bundle) UpdateDatabaseConnections

func (b *Bundle) UpdateDatabaseConnections(active, idle int)

UpdateDatabaseConnections updates database connection pool metrics.

func (*Bundle) UpdateRedisConnections

func (b *Bundle) UpdateRedisConnections(active, idle int)

UpdateRedisConnections updates Redis connection pool metrics.

type Config

type Config struct {
	// Namespace for all metrics (typically service name)
	Namespace string

	// Subsystem for metrics grouping (optional)
	Subsystem string

	// Metric collection configuration
	EnableDefaultMetrics bool // Enable Go runtime metrics (memory, GC, etc.)
	EnableHTTPMetrics    bool // Enable HTTP request/response metrics
	EnableGRPCMetrics    bool // Enable gRPC call metrics
	EnableHealthMetrics  bool // Enable health check metrics
	EnableBundleMetrics  bool // Enable bundle-specific metrics (DB, Redis, etc.)

	// Custom registry (optional - uses global registry if nil)
	Registry prometheus.Registerer

	// Metric label configuration
	ServiceLabels map[string]string // Additional labels for all metrics

	// Performance configuration
	HistogramBuckets []float64 // Custom histogram buckets for latency metrics
}

Config contains Prometheus metrics configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the Prometheus configuration.

type MetricsCollector

type MetricsCollector interface {
	// CollectMetrics should update Prometheus metrics with current state.
	CollectMetrics(ctx context.Context, bundle *Bundle) error
}

MetricsCollector provides an interface for components to expose metrics.

type PrometheusHealthCheck

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

PrometheusHealthCheck implements health checking for Prometheus metrics.

func (*PrometheusHealthCheck) Liveness

func (c *PrometheusHealthCheck) Liveness(ctx context.Context) error

Liveness performs a basic metrics system check.

func (*PrometheusHealthCheck) Name

func (c *PrometheusHealthCheck) Name() string

Name returns the health check name.

func (*PrometheusHealthCheck) Readiness

func (c *PrometheusHealthCheck) Readiness(ctx context.Context) error

Readiness performs a comprehensive metrics system check.

type SecurityConfig

type SecurityConfig struct {
	MaxRequestsInFlight int           // Maximum concurrent requests (default: 3)
	Timeout             time.Duration // Request timeout (default: 10s)
	EnableBasicAuth     bool          // Enable basic authentication
	Username            string        // Basic auth username
	Password            string        // Basic auth password
}

SecurityConfig contains security configuration for the metrics endpoint.

func DefaultSecurityConfig

func DefaultSecurityConfig() SecurityConfig

DefaultSecurityConfig returns secure defaults for metrics endpoint.

Jump to

Keyboard shortcuts

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