-
Notifications
You must be signed in to change notification settings - Fork 0
Monitoring
Mohammad Rajabloo edited this page Aug 10, 2024
·
1 revision
if you are using Prometheus for monitoring you can copy this code to you project:
package metrics
import (
"context"
"fmt"
"github.com/mrsoftware/circuitbreaker"
"github.com/prometheus/client_golang/prometheus"
)
var _ prometheus.Collector = &CircuitCollector{}
const (
circuitBreakerSystem = "circuit_breaker"
)
// CircuitCollector is used to collect circuit breaker stat using prometheus.
type CircuitCollector struct {
circuit circuitbreaker.Manager
State *prometheus.Desc
Success *prometheus.Desc
Failure *prometheus.Desc
}
// NewCircuitCollector create new CircuitCollector.
func NewCircuitCollector(service, name string, circuit circuitbreaker.Manager) *CircuitCollector {
return &CircuitCollector{
circuit: circuit,
State: prometheus.NewDesc(
prometheus.BuildFQName(
service, circuitBreakerSystem, fmt.Sprintf("%s_state", name),
),
fmt.Sprintf("state of circuit breaker for %s service", name),
nil, nil,
),
Failure: prometheus.NewDesc(
prometheus.BuildFQName(
service, circuitBreakerSystem, fmt.Sprintf("%s_failure_total", name),
),
fmt.Sprintf("failure count of circuit breaker for %s service", name),
nil, nil,
),
Success: prometheus.NewDesc(
prometheus.BuildFQName(
service, circuitBreakerSystem, fmt.Sprintf("%s_success_total", name),
),
fmt.Sprintf("success count of circuit breaker for %s service", name),
nil, nil,
),
}
}
// Describe give the collector descriptions about this collector metrics.
func (c *CircuitCollector) Describe(descs chan<- *prometheus.Desc) {
// the Collect method will always return the same two metrics with the same two descriptors.
prometheus.DescribeByCollect(c, descs)
}
// Collect implement prometheus collector Collect and used to give the collected metrics about ants.
func (c *CircuitCollector) Collect(metrics chan<- prometheus.Metric) {
stat := c.circuit.Stat(context.Background())
// collect current state.
metrics <- prometheus.MustNewConstMetric(c.State, prometheus.GaugeValue, float64(stat.State))
// collect failure count.
metrics <- prometheus.MustNewConstMetric(c.Failure, prometheus.CounterValue, float64(stat.Failure))
// collect success count.
metrics <- prometheus.MustNewConstMetric(c.Success, prometheus.CounterValue, float64(stat.Success))
}
make sure the metric is registered using prometheus.Register
function.