From 4968bc66f01922cdf0e5bb6cbf891e99a10bb814 Mon Sep 17 00:00:00 2001 From: Wolfy-J Date: Wed, 26 Jun 2019 16:38:52 +0300 Subject: custom application metrics --- service/metrics/rpc.go | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 service/metrics/rpc.go (limited to 'service/metrics/rpc.go') diff --git a/service/metrics/rpc.go b/service/metrics/rpc.go new file mode 100644 index 00000000..5d1b8102 --- /dev/null +++ b/service/metrics/rpc.go @@ -0,0 +1,72 @@ +package metrics + +import ( + "fmt" + "github.com/prometheus/client_golang/prometheus" +) + +type rpcServer struct{ svc *Service } + +type Metric struct { + // Collector name. + Name string + + // Collector value. + Value float64 + + // Labels associated with metric. Only for vector metrics. + Labels []string +} + +// Add new metric to the designated collector. +func (rpc *rpcServer) Add(m *Metric, ok *bool) error { + c := rpc.svc.Collector(m.Name) + if c == nil { + return fmt.Errorf("undefined collector `%s`", m.Name) + } + + switch c.(type) { + case prometheus.Gauge: + c.(prometheus.Gauge).Add(m.Value) + + case *prometheus.GaugeVec: + if len(m.Labels) == 0 { + return fmt.Errorf("required labels for collector `%s`", m.Name) + } + + c.(*prometheus.GaugeVec).WithLabelValues(m.Labels...).Add(m.Value) + + case prometheus.Counter: + c.(prometheus.Counter).Add(m.Value) + + case *prometheus.CounterVec: + if len(m.Labels) == 0 { + return fmt.Errorf("required labels for collector `%s`", m.Name) + } + + c.(*prometheus.CounterVec).WithLabelValues(m.Labels...).Add(m.Value) + + case prometheus.Summary: + c.(prometheus.Counter).Add(m.Value) + + case *prometheus.SummaryVec: + if len(m.Labels) == 0 { + return fmt.Errorf("required labels for collector `%s`", m.Name) + } + + c.(*prometheus.SummaryVec).WithLabelValues(m.Labels...).Observe(m.Value) + + case prometheus.Histogram: + c.(prometheus.Histogram).Observe(m.Value) + + case *prometheus.HistogramVec: + if len(m.Labels) == 0 { + return fmt.Errorf("required labels for collector `%s`", m.Name) + } + + c.(*prometheus.HistogramVec).WithLabelValues(m.Labels...).Observe(m.Value) + } + + *ok = true + return nil +} -- cgit v1.2.3