/
prometheus.go
73 lines (62 loc) · 2.12 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
package prometheus
import (
"net/http"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/grpc"
)
// returns a grpc server pre-configured with prometheus interceptors
func NewGrpcServer() *grpc.Server {
server := grpc.NewServer(
grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
)
grpc_prometheus.EnableHandlingTimeHistogram()
grpc_prometheus.Register(server)
return server
}
// define latency buckets to record (seconds)
var RequestDurationBucketsSeconds = append(append(append(append(
prometheus.LinearBuckets(0.01, 0.01, 5),
prometheus.LinearBuckets(0.1, 0.1, 5)...),
prometheus.LinearBuckets(1, 1, 5)...),
prometheus.LinearBuckets(10, 10, 5)...),
)
// define response size buckets (bytes)
var ResponseSizeBuckets = append(append(append(append(
prometheus.LinearBuckets(100, 100, 5),
prometheus.LinearBuckets(1000, 1000, 5)...),
prometheus.LinearBuckets(10000, 10000, 5)...),
prometheus.LinearBuckets(1000000, 1000000, 5)...),
)
// instrument HTTP server with prometheus
func WithTelemetry(handler http.Handler) http.HandlerFunc {
counter := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "A counter for requests to the wrapped handler.",
},
[]string{"code"},
)
duration := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "A histogram of latencies for requests in seconds.",
Buckets: RequestDurationBucketsSeconds,
},
[]string{"code"},
)
responseSize := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_response_size_bytes",
Help: "A histogram of response sizes for requests.",
Buckets: ResponseSizeBuckets,
},
[]string{},
)
prometheus.MustRegister(counter, duration, responseSize)
return promhttp.InstrumentHandlerDuration(duration,
promhttp.InstrumentHandlerResponseSize(responseSize,
promhttp.InstrumentHandlerCounter(counter, handler)))
}