micro-meter-prometheus/prometheus.go

50 lines
1.2 KiB
Go
Raw Normal View History

package prometheus
import (
"context"
"github.com/micro/go-micro/server"
"github.com/prometheus/client_golang/prometheus"
)
func NewHandlerWrapper() server.HandlerWrapper {
opsCounter := prometheus.NewCounterVec(
prometheus.CounterOpts{
2019-01-25 19:12:34 +03:00
Name: "micro_request_total",
2019-01-25 19:11:45 +03:00
Help: "How many go-micro requests processed, partitioned by method and status",
},
[]string{"method", "status"},
)
timeCounter := prometheus.NewSummaryVec(
prometheus.SummaryOpts{
2019-01-25 19:11:45 +03:00
Name: "micro_request_duration_microseconds",
Help: "Service method request latencies in microseconds",
},
[]string{"method"},
)
prometheus.MustRegister(opsCounter)
prometheus.MustRegister(timeCounter)
return func(fn server.HandlerFunc) server.HandlerFunc {
return func(ctx context.Context, req server.Request, rsp interface{}) error {
name := req.Endpoint()
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
us := v * 1000000 // make microseconds
timeCounter.WithLabelValues(name).Observe(us)
}))
defer timer.ObserveDuration()
err := fn(ctx, req, rsp)
if err == nil {
opsCounter.WithLabelValues(name, "success").Inc()
} else {
opsCounter.WithLabelValues(name, "fail").Inc()
}
return err
}
}
}