-
Notifications
You must be signed in to change notification settings - Fork 91
/
prometheus.go
79 lines (65 loc) · 2.05 KB
/
prometheus.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package prometheus
import (
"strconv"
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/context"
"github.com/prometheus/client_golang/prometheus"
)
func init() {
context.SetHandlerName("github.com/iris-contrib/middleware/prometheus.*", "iris-contrib.prometheus")
}
var (
// DefaultBuckets prometheus buckets in seconds.
DefaultBuckets = []float64{0.3, 1.2, 5.0}
)
const (
reqsName = "http_requests_total"
latencyName = "http_request_duration_seconds"
)
// Prometheus is a handler that exposes prometheus metrics for the number of requests,
// the latency and the response size, partitioned by status code, method and HTTP path.
//
// Usage: pass its `ServeHTTP` to a route or globally.
type Prometheus struct {
reqs *prometheus.CounterVec
latency *prometheus.HistogramVec
}
// New returns a new prometheus middleware.
//
// If buckets are empty then `DefaultBuckets` are set.
func New(name string, buckets ...float64) *Prometheus {
p := Prometheus{}
p.reqs = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: reqsName,
Help: "How many HTTP requests processed, partitioned by status code, method and HTTP path.",
ConstLabels: prometheus.Labels{"service": name},
},
[]string{"code", "method", "path"},
)
prometheus.MustRegister(p.reqs)
if len(buckets) == 0 {
buckets = DefaultBuckets
}
p.latency = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: latencyName,
Help: "How long it took to process the request, partitioned by status code, method and HTTP path.",
ConstLabels: prometheus.Labels{"service": name},
Buckets: buckets,
},
[]string{"code", "method", "path"},
)
prometheus.MustRegister(p.latency)
return &p
}
func (p *Prometheus) ServeHTTP(ctx iris.Context) {
start := time.Now()
ctx.Next()
r := ctx.Request()
statusCode := strconv.Itoa(ctx.GetStatusCode())
p.reqs.WithLabelValues(statusCode, r.Method, r.URL.Path).
Inc()
p.latency.WithLabelValues(statusCode, r.Method, r.URL.Path).
Observe(float64(time.Since(start).Nanoseconds()) / 1000000000)
}