-
Notifications
You must be signed in to change notification settings - Fork 3
/
metrics.go
96 lines (81 loc) · 2.6 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
package main
import (
"fmt"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/push"
"github.com/rs/zerolog"
)
var (
httpRequestsResponseTime prometheus.Histogram
httpRequestsCount *prometheus.CounterVec
httpRemoteAddresses *prometheus.CounterVec
httpResponseCodes *prometheus.CounterVec
)
// Register the prometheus metrics/collectors
func init() {
httpRequestsResponseTime = prometheus.NewHistogram(prometheus.HistogramOpts{
Namespace: "http",
Name: "response_time_seconds",
Help: "Request response times",
})
httpRequestsCount = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "http",
Name: "requests_count",
Help: "Request counter",
}, []string{"http_method", "http_request_uri", "endpoint"})
httpRemoteAddresses = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "http",
Name: "remote_addr",
Help: "Remote addresses counter",
}, []string{"http_remote_addr"})
httpResponseCodes = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "http",
Name: "response_code",
Help: "Response codes counter",
}, []string{"http_response_code"})
prometheus.MustRegister(httpRequestsResponseTime)
prometheus.MustRegister(httpRequestsCount)
prometheus.MustRegister(httpRemoteAddresses)
prometheus.MustRegister(httpResponseCodes)
}
// Send metrics to Prometheus
func pushMetrics(log *zerolog.Logger, elapsed time.Duration, request *http.Request, response *http.Response) {
httpRequestsResponseTime.Observe(float64(elapsed))
httpRequestsCount.With(prometheus.Labels{
"http_method": request.Method,
"http_request_uri": request.RequestURI,
"endpoint": fmt.Sprint(request.URL),
}).Add(1)
err := push.Collectors(
"http", push.HostnameGroupingKey(),
"http://metrics-gateway:9091",
httpRequestsCount,
)
if err != nil {
log.Error().Err(err).Msg("could not push response time to prometheus")
}
httpRemoteAddresses.With(prometheus.Labels{
"http_remote_addr": request.RemoteAddr,
}).Add(1)
err = push.Collectors(
"http", push.HostnameGroupingKey(),
"http://metrics-gateway:9091",
httpRemoteAddresses,
)
if err != nil {
log.Error().Err(err).Msg("could not push remote addresses to prometheus")
}
httpResponseCodes.With(prometheus.Labels{
"http_response_code": fmt.Sprint(response.StatusCode),
}).Add(1)
err = push.Collectors(
"http", push.HostnameGroupingKey(),
"http://metrics-gateway:9091",
httpResponseCodes,
)
if err != nil {
log.Error().Err(err).Msg("could not push response codes to prometheus")
}
}