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 ¶
- type Bundle
- func (b *Bundle) CollectConnectionMetrics(ctx context.Context, app *framework.App)
- func (b *Bundle) CreateCustomCounter(name, help string, labelNames []string) (*prometheus.CounterVec, error)
- func (b *Bundle) CreateCustomGauge(name, help string, labelNames []string) (*prometheus.GaugeVec, error)
- func (b *Bundle) CreateCustomHistogram(name, help string, labelNames []string) (*prometheus.HistogramVec, error)
- func (b *Bundle) CreateCustomSummary(name, help string, labelNames []string, objectives map[float64]float64) (*prometheus.SummaryVec, error)
- func (b *Bundle) Gatherer() prometheus.Gatherer
- func (b *Bundle) HTTPMiddleware() func(http.Handler) http.Handler
- func (b *Bundle) HealthChecks() []forgeHealth.Check
- func (b *Bundle) Initialize(app *framework.App) error
- func (b *Bundle) MetricsHandler() http.Handler
- func (b *Bundle) Name() string
- func (b *Bundle) RecordGRPCRequest(method, statusCode string, duration time.Duration)
- func (b *Bundle) RecordHTTPRequest(method, endpoint string, statusCode int, duration time.Duration)
- func (b *Bundle) RecordHealthCheck(checkName, checkType string, success bool, duration time.Duration)
- func (b *Bundle) RecordJWTValidation(success bool, service string)
- func (b *Bundle) Registry() prometheus.Registerer
- func (b *Bundle) SecureMetricsHandler(secConfig SecurityConfig) http.Handler
- func (b *Bundle) StartMetricsCollection(ctx context.Context, collectors []MetricsCollector, interval time.Duration)
- func (b *Bundle) Stop(ctx context.Context) error
- func (b *Bundle) StreamServerInterceptor() grpc.StreamServerInterceptor
- func (b *Bundle) UnaryServerInterceptor() grpc.UnaryServerInterceptor
- func (b *Bundle) UpdateCircuitBreakerState(name string, state int)
- func (b *Bundle) UpdateDatabaseConnections(active, idle int)
- func (b *Bundle) UpdateRedisConnections(active, idle int)
- type Config
- type MetricsCollector
- type PrometheusHealthCheck
- type SecurityConfig
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 (*Bundle) CollectConnectionMetrics ¶
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) HTTPMiddleware ¶ added in v0.3.0
HTTPMiddleware returns HTTP middleware that automatically records RecordHTTPRequest metrics for every request.
The endpoint label prefers r.Pattern, the matched net/http.ServeMux pattern (e.g. "GET /users/{id}"), which the framework's mux populates before invoking the handler. That keeps the label a bounded route template rather than raw concrete paths. It falls back to r.URL.Path only for requests that matched no route (e.g. 404s), where cardinality is naturally limited by what clients actually request.
func (*Bundle) HealthChecks ¶
func (b *Bundle) HealthChecks() []forgeHealth.Check
HealthChecks returns health checks for the Prometheus metrics system.
func (*Bundle) Initialize ¶
Initialize sets up Prometheus metrics collection.
func (*Bundle) MetricsHandler ¶ added in v0.3.0
MetricsHandler returns an HTTP handler for the /metrics endpoint with basic security.
func (*Bundle) RecordGRPCRequest ¶
RecordGRPCRequest records metrics for a gRPC request.
func (*Bundle) RecordHTTPRequest ¶
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 ¶
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) SecureMetricsHandler ¶ added in v0.3.0
func (b *Bundle) SecureMetricsHandler(secConfig SecurityConfig) http.Handler
SecureMetricsHandler returns a secured HTTP handler for the /metrics endpoint.
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 ¶
Stop implements the Bundle interface for graceful shutdown. Prometheus bundle has no persistent resources requiring cleanup.
func (*Bundle) StreamServerInterceptor ¶ added in v0.3.0
func (b *Bundle) StreamServerInterceptor() grpc.StreamServerInterceptor
StreamServerInterceptor returns a gRPC stream server interceptor that automatically records RecordGRPCRequest metrics for every streaming call. See UnaryServerInterceptor for how the status label is derived.
func (*Bundle) UnaryServerInterceptor ¶ added in v0.3.0
func (b *Bundle) UnaryServerInterceptor() grpc.UnaryServerInterceptor
UnaryServerInterceptor returns a gRPC unary server interceptor that automatically records RecordGRPCRequest metrics for every unary call. The status label is derived from the returned error via gRPC status codes (e.g. "OK", "NotFound", "Internal"), so a nil error always records "OK".
func (*Bundle) UpdateCircuitBreakerState ¶
UpdateCircuitBreakerState updates circuit breaker state metrics.
func (*Bundle) UpdateDatabaseConnections ¶
UpdateDatabaseConnections updates database connection pool metrics.
func (*Bundle) UpdateRedisConnections ¶
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.
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.
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.