From d927ad4673d1b1255c70e51b382dff3f0a78bada Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Mon, 4 Feb 2019 01:26:31 +0300 Subject: [PATCH] wrapper: prometheus attach labels to all metrics Signed-off-by: Vasiliy Tolstov --- prometheus.go | 30 ++++++++++++++++++------------ prometheus_test.go | 4 ++++ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/prometheus.go b/prometheus.go index e3550b1..c9f391c 100644 --- a/prometheus.go +++ b/prometheus.go @@ -35,34 +35,40 @@ func NewHandlerWrapper(opts ...server.Option) server.HandlerWrapper { opsCounter := prometheus.NewCounterVec( prometheus.CounterOpts{ - Name: fmt.Sprintf("%s_request_total", defaultMetricPrefix), - Help: "How many go-micro requests processed, partitioned by method and status", - ConstLabels: md, + Name: fmt.Sprintf("%s_request_total", defaultMetricPrefix), + Help: "How many go-micro requests processed, partitioned by method and status", }, []string{"method", "status"}, ) timeCounterSummary := prometheus.NewSummaryVec( prometheus.SummaryOpts{ - Name: fmt.Sprintf("%s_upstream_latency_microseconds", defaultMetricPrefix), - Help: "Service backend method request latencies in microseconds", - ConstLabels: md, + Name: fmt.Sprintf("%s_upstream_latency_microseconds", defaultMetricPrefix), + Help: "Service backend method request latencies in microseconds", }, []string{"method"}, ) timeCounterHistogram := prometheus.NewHistogramVec( prometheus.HistogramOpts{ - Name: fmt.Sprintf("%s_request_duration_seconds", defaultMetricPrefix), - Help: "Service method request time in seconds", - ConstLabels: md, + Name: fmt.Sprintf("%s_request_duration_seconds", defaultMetricPrefix), + Help: "Service method request time in seconds", }, []string{"method"}, ) - prometheus.MustRegister(opsCounter) - prometheus.MustRegister(timeCounterSummary) - prometheus.MustRegister(timeCounterHistogram) + reg := prometheus.NewRegistry() + wrapreg := prometheus.WrapRegistererWith(md, reg) + wrapreg.MustRegister( + prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}), + prometheus.NewGoCollector(), + opsCounter, + timeCounterSummary, + timeCounterHistogram, + ) + + prometheus.DefaultGatherer = reg + prometheus.DefaultRegisterer = wrapreg return func(fn server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { diff --git a/prometheus_test.go b/prometheus_test.go index 9fffe86..451d74c 100644 --- a/prometheus_test.go +++ b/prometheus_test.go @@ -87,6 +87,10 @@ func TestPrometheusMetrics(t *testing.T) { metric := findMetricByName(list, dto.MetricType_SUMMARY, "micro_upstream_latency_microseconds") + if metric == nil || metric.Metric == nil || len(metric.Metric) == 0 { + t.Fatalf("no metrics returned") + } + for _, v := range metric.Metric[0].Label { switch *v.Name { case "micro_dc":