metrics.go 1.46 KB
Newer Older
1 2 3 4
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

Janos Guljas's avatar
Janos Guljas committed
5 6 7 8 9 10
package api

import (
	"net/http"
	"time"

11
	m "github.com/ethersphere/bee/pkg/metrics"
Janos Guljas's avatar
Janos Guljas committed
12 13 14 15 16 17 18 19 20 21 22 23
	"github.com/prometheus/client_golang/prometheus"
)

type metrics struct {
	// all metrics fields must be exported
	// to be able to return them by Metrics()
	// using reflection
	RequestCount     prometheus.Counter
	ResponseDuration prometheus.Histogram
	PingRequestCount prometheus.Counter
}

24 25 26
func newMetrics() metrics {
	subsystem := "api"

Janos Guljas's avatar
Janos Guljas committed
27 28
	return metrics{
		RequestCount: prometheus.NewCounter(prometheus.CounterOpts{
29 30 31 32
			Namespace: m.Namespace,
			Subsystem: subsystem,
			Name:      "request_count",
			Help:      "Number of API requests.",
Janos Guljas's avatar
Janos Guljas committed
33 34
		}),
		ResponseDuration: prometheus.NewHistogram(prometheus.HistogramOpts{
35 36 37 38 39
			Namespace: m.Namespace,
			Subsystem: subsystem,
			Name:      "response_duration_seconds",
			Help:      "Histogram of API response durations.",
			Buckets:   []float64{0.01, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
Janos Guljas's avatar
Janos Guljas committed
40 41 42 43
		}),
	}
}

44 45
func (s *server) Metrics() []prometheus.Collector {
	return m.PrometheusCollectorsFromFields(s.metrics)
Janos Guljas's avatar
Janos Guljas committed
46 47 48 49 50 51 52 53 54 55
}

func (s *server) pageviewMetricsHandler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		s.metrics.RequestCount.Inc()
		h.ServeHTTP(w, r)
		s.metrics.ResponseDuration.Observe(time.Since(start).Seconds())
	})
}