This repository has been archived by the owner on Sep 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
metrics.go
102 lines (88 loc) · 2.27 KB
/
metrics.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"fmt"
"log"
"math"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
)
var codes = []int{}
var (
// HTTPRequestsTotalCounter is the global http request counter
HTTPRequestsTotalCounter *prometheus.CounterVec
// HTTPRequestsDuration is the global http request duration histogram
HTTPRequestsDuration *prometheus.HistogramVec
// HTTPRequestsSize is the global http request size histogram
HTTPRequestsSize *prometheus.HistogramVec
)
func init() {
HTTPRequestsTotalCounter = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "staticsrv_http_requests_total",
Help: "The total number of processed HTTP requests for staticsrv",
}, []string{"method", "status"})
if err := prometheus.Register(HTTPRequestsTotalCounter); err != nil {
log.Fatal(err)
}
HTTPRequestsDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "staticsrv_http_requests_duration_seconds",
Help: "Time it has taken to process HTTP requests for staticsrv",
Buckets: []float64{
0.0001,
0.0005,
0.001,
0.005,
0.01,
0.05,
0.1,
1,
2,
5,
10,
math.Inf(+1),
},
}, []string{})
if err := prometheus.Register(HTTPRequestsDuration); err != nil {
log.Fatal(err)
}
HTTPRequestsSize = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "staticsrv_http_requests_size_bytes",
Help: "Bytes written to the client over HTTP for staticsrv",
Buckets: []float64{
0,
2,
4,
8,
16,
32,
64,
128,
256,
512,
1024,
2048,
4094,
8192,
math.Inf(+1),
},
}, []string{})
if err := prometheus.Register(HTTPRequestsSize); err != nil {
log.Fatal(err)
}
}
// MetricsMiddleware will handle every HTTP request and increment the request counter.
func MetricsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(wr http.ResponseWriter, r *http.Request) {
start := time.Now()
lrw := NewLoggingResponseWriter(wr)
next.ServeHTTP(lrw, r)
end := time.Now()
duration := end.Sub(start)
HTTPRequestsTotalCounter.With(prometheus.Labels{
"status": fmt.Sprintf("%d", lrw.StatusCode),
"method": r.Method,
}).Inc()
HTTPRequestsDuration.WithLabelValues().Observe(duration.Seconds())
HTTPRequestsSize.WithLabelValues().Observe(float64(lrw.BytesWritten))
})
}