arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/metric/request.go
metric/request.goRaw
 1package metric
 2
 3import (
 4	"strconv"
 5	"time"
 6
 7	"github.com/gin-gonic/gin"
 8	"github.com/prometheus/client_golang/prometheus"
 9)
10
11const (
12	favicon = "/favicon.ico"
13)
14
15// Prometheus contains the metrics gathered by the instance and its path
16type Prometheus struct {
17	reqCnt *prometheus.CounterVec
18	reqDur *prometheus.HistogramVec
19}
20
21// NewPrometheus generates a new set of metrics with a certain subsystem name
22func NewPrometheus() (*Prometheus, error) {
23	reqCnt := prometheus.NewCounterVec(
24		prometheus.CounterOpts{
25			Namespace: namespaceAPI,
26			Name:      "requests_total",
27			Help:      "How many HTTP requests processed, partitioned by status code and HTTP method",
28		},
29		[]string{"code", "method", "path"},
30	)
31	if err := registerCollector(reqCnt); err != nil {
32		return nil, err
33	}
34	reqDur := prometheus.NewHistogramVec(
35		prometheus.HistogramOpts{
36			Namespace: namespaceAPI,
37			Name:      "request_duration_seconds",
38			Help:      "The HTTP request latencies in seconds",
39		},
40		[]string{"code", "method", "path"},
41	)
42	if err := registerCollector(reqDur); err != nil {
43		return nil, err
44	}
45	return &Prometheus{
46		reqCnt: reqCnt,
47		reqDur: reqDur,
48	}, nil
49}
50
51// PrometheusMiddleware creates the prometheus collector and
52// defines status handler function for the middleware
53func PrometheusMiddleware() (gin.HandlerFunc, error) {
54	p, err := NewPrometheus()
55	if err != nil {
56		return nil, err
57	}
58	return p.Middleware(), nil
59}
60
61// Middleware defines status handler function for middleware
62func (p *Prometheus) Middleware() gin.HandlerFunc {
63	return func(c *gin.Context) {
64		if c.Request.URL.Path == favicon {
65			c.Next()
66			return
67		}
68		start := time.Now()
69		c.Next()
70
71		status := strconv.Itoa(c.Writer.Status())
72		elapsed := float64(time.Since(start)) / float64(time.Second)
73		fullPath := c.FullPath()
74
75		p.reqDur.WithLabelValues(status, c.Request.Method, fullPath).Observe(elapsed)
76		p.reqCnt.WithLabelValues(status, c.Request.Method, fullPath).Inc()
77	}
78}