http.go64 lines, 1.9 KB
| 1 | package metrics |
| 2 | |
| 3 | import ( |
| 4 | "cmp" |
| 5 | "net/http" |
| 6 | "strconv" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/prometheus/client_golang/prometheus" |
| 10 | ) |
| 11 | |
| 12 | // HTTP counts the requests a server answers, and how long they took. |
| 13 | type HTTP struct { |
| 14 | requests *prometheus.CounterVec |
| 15 | duration *prometheus.HistogramVec |
| 16 | } |
| 17 | |
| 18 | func NewHTTP(reg prometheus.Registerer) *HTTP { |
| 19 | m := &HTTP{ |
| 20 | requests: prometheus.NewCounterVec(prometheus.CounterOpts{ |
| 21 | Name: "http_requests_total", |
| 22 | Help: "Requests answered, by route and status.", |
| 23 | }, []string{"route", "status"}), |
| 24 | duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ |
| 25 | Name: "http_request_duration_seconds", |
| 26 | Help: "How long a request took, by route.", |
| 27 | Buckets: []float64{.005, .01, .015, .02, .03, .04, .06, .08, .1, .15, .25, .5, 1, 2.5, 10}, |
| 28 | }, []string{"route"}), |
| 29 | } |
| 30 | reg.MustRegister(m.requests, m.duration) |
| 31 | return m |
| 32 | } |
| 33 | |
| 34 | // A recorder remembers the status code that a handler sends. |
| 35 | type recorder struct { |
| 36 | http.ResponseWriter |
| 37 | status int |
| 38 | } |
| 39 | |
| 40 | func (rec *recorder) WriteHeader(status int) { |
| 41 | rec.status = status |
| 42 | rec.ResponseWriter.WriteHeader(status) |
| 43 | } |
| 44 | |
| 45 | // Unwrap hands out the real writer. http.ResponseController asks for it, |
| 46 | // when a handler wants to flush or to set a deadline. |
| 47 | func (rec *recorder) Unwrap() http.ResponseWriter { |
| 48 | return rec.ResponseWriter |
| 49 | } |
| 50 | |
| 51 | // Wrap measures every request that goes through next. |
| 52 | func (m *HTTP) Wrap(next http.HandlerFunc) http.HandlerFunc { |
| 53 | return func(w http.ResponseWriter, r *http.Request) { |
| 54 | start := time.Now() |
| 55 | rec := &recorder{ResponseWriter: w, status: http.StatusOK} |
| 56 | next(rec, r) |
| 57 | route := cmp.Or(r.Pattern, "other") |
| 58 | m.requests.WithLabelValues(route, strconv.Itoa(rec.status)).Inc() |
| 59 | if rec.Header().Get("Content-Type") == "text/event-stream" { |
| 60 | return // a stream is open for minutes: it's counted, but it's not a slow request |
| 61 | } |
| 62 | m.duration.WithLabelValues(route).Observe(time.Since(start).Seconds()) |
| 63 | } |
| 64 | } |