-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathhandler.go
More file actions
68 lines (56 loc) · 2.11 KB
/
Copy pathhandler.go
File metadata and controls
68 lines (56 loc) · 2.11 KB
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
package metrics
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// HTTPHandlerOpts configures HTTP instrumentation metrics.
type HTTPHandlerOpts struct {
DurationBuckets []float64
RequestSizeBuckets []float64
ResponseSizeBuckets []float64
}
// HTTPMetric describes a metric used to instrument an HTTP handler.
//
// HTTPMetric values must be created using the HTTP metric methods on
// [Namespace], such as [Namespace.NewDefaultHttpMetrics] or
// [Namespace.NewHttpMetricsWithOpts].
type HTTPMetric struct {
collector prometheus.Collector
wrap func(http.Handler) http.Handler
}
var _ prometheus.Collector = (*HTTPMetric)(nil)
// Describe implements [prometheus.Collector].
func (m *HTTPMetric) Describe(ch chan<- *prometheus.Desc) {
m.collector.Describe(ch)
}
// Collect implements [prometheus.Collector].
func (m *HTTPMetric) Collect(ch chan<- prometheus.Metric) {
m.collector.Collect(ch)
}
var (
defaultDurationBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 25, 60}
defaultRequestSizeBuckets = prometheus.ExponentialBuckets(1024, 2, 22) // 1K to 4G
defaultResponseSizeBuckets = defaultRequestSizeBuckets
)
// Handler is a convenience wrapper around [promhttp.Handler] that returns an
// HTTP handler serving metrics from the default Prometheus gatherer.
func Handler() http.Handler {
return promhttp.Handler()
}
// InstrumentHandler returns an HTTP handler function that instruments handler
// with the provided HTTP metrics.
func InstrumentHandler(metrics []*HTTPMetric, handler http.Handler) http.HandlerFunc {
return instrumentHandler(metrics, handler)
}
// InstrumentHandlerFunc returns an HTTP handler function that instruments
// handlerFunc with the provided HTTP metrics.
func InstrumentHandlerFunc(metrics []*HTTPMetric, handlerFunc http.HandlerFunc) http.HandlerFunc {
return instrumentHandler(metrics, handlerFunc)
}
func instrumentHandler(metrics []*HTTPMetric, handler http.Handler) http.HandlerFunc {
for _, metric := range metrics {
handler = metric.wrap(handler)
}
return handler.ServeHTTP
}