aboutsummaryrefslogtreecommitdiff
path: root/echo/prometheus/prometheus.go
blob: 2fbf25241a23dfebc9b3e513146ec92130571a22 (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package prometheus

import (
	"errors"
	"net/http"
	"strconv"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

type Prometheus struct {
	Config          *PrometheusConfig
	requestCount    *prometheus.CounterVec
	requestDuration *prometheus.HistogramVec
	requestSize     *prometheus.HistogramVec
	responseSize    *prometheus.HistogramVec
	MetricsHandler  echo.HandlerFunc
}

type PrometheusConfig struct {
	Skipper      middleware.Skipper
	ExtractUrl   func(c echo.Context) string
	ExtractHost  func(c echo.Context) string
	ContextLabel string // Context var name to use as a prometheus URL label
	MetricsPath  string
	Subsystem    string
}

var DefaultPrometheusConfig = &PrometheusConfig{
	Skipper: middleware.DefaultSkipper,
	ExtractUrl: func(c echo.Context) string {
		return c.Path()
	},
	ExtractHost: func(c echo.Context) string {
		return c.Request().Host
	},
	MetricsPath: "/metrics",
	Subsystem:   "echo",
}

func NewPrometheus() *Prometheus {
	return NewPrometheusWithConfig(DefaultPrometheusConfig)
}

func NewPrometheusWithConfig(c *PrometheusConfig) *Prometheus {
	if c.Subsystem == "" {
		c.Subsystem = DefaultPrometheusConfig.Subsystem
	}
	if c.MetricsPath == "" {
		c.MetricsPath = DefaultPrometheusConfig.MetricsPath
	}
	if c.Skipper == nil {
		c.Skipper = middleware.DefaultSkipper
	}
	if c.ExtractUrl == nil {
		c.ExtractUrl = DefaultPrometheusConfig.ExtractUrl
	}
	if c.ExtractHost == nil {
		c.ExtractHost = DefaultPrometheusConfig.ExtractHost
	}

	return &Prometheus{
		Config:         c,
		MetricsHandler: echo.WrapHandler(promhttp.Handler()),
		requestCount: promauto.NewCounterVec(prometheus.CounterOpts{
			Subsystem: c.Subsystem,
			Name:      "requests_total",
			Help:      "How many HTTP requests processed, partitioned by status code and HTTP method.",
		}, []string{"code", "method", "host", "url"}),
		requestDuration: promauto.NewHistogramVec(prometheus.HistogramOpts{
			Subsystem: c.Subsystem,
			Name:      "request_duration_seconds",
			Help:      "The HTTP request latencies in seconds.",
		}, []string{"code", "method", "url"}),
		requestSize: promauto.NewHistogramVec(prometheus.HistogramOpts{
			Subsystem: c.Subsystem,
			Name:      "response_size_bytes",
			Help:      "The HTTP response sizes in bytes.",
		}, []string{"code", "method", "url"}),
		responseSize: promauto.NewHistogramVec(prometheus.HistogramOpts{
			Subsystem: c.Subsystem,
			Name:      "request_size_bytes",
			Help:      "The HTTP request sizes in bytes.",
		}, []string{"code", "method", "url"}),
	}
}

func (p *Prometheus) MiddlewareHandler(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		if c.Path() == p.Config.MetricsPath {
			return next(c)
		}

		if p.Config.Skipper(c) {
			return next(c)
		}

		start := time.Now()
		reqSz := computeApproximateRequestSize(c.Request())
		err := next(c)
		elapsed := float64(time.Since(start)) / float64(time.Second)

		status := c.Response().Status
		if err != nil {
			var httpError *echo.HTTPError
			if errors.As(err, &httpError) {
				status = httpError.Code
			}
			if status == 0 || status == http.StatusOK {
				status = http.StatusInternalServerError
			}
		}

		url := p.Config.ExtractUrl(c)
		if len(p.Config.ContextLabel) > 0 {
			u := c.Get(p.Config.ContextLabel)
			if u == nil {
				u = "unknown"
			}
			url = u.(string)
		}

		s := strconv.Itoa(status)
		m := c.Request().Method
		p.requestDuration.WithLabelValues(s, m, url).Observe(elapsed)
		p.requestCount.WithLabelValues(s, m, p.Config.ExtractHost(c), url).Inc()
		p.requestSize.WithLabelValues(s, m, url).Observe(float64(reqSz))
		p.responseSize.WithLabelValues(s, m, url).Observe(float64(c.Response().Size))

		return err
	}
}

func computeApproximateRequestSize(r *http.Request) int {
	s := 0
	if r.URL != nil {
		s = len(r.URL.Path)
	}

	s += len(r.Method)
	s += len(r.Proto)
	for name, values := range r.Header {
		s += len(name)
		for _, value := range values {
			s += len(value)
		}
	}
	s += len(r.Host)

	if r.ContentLength != -1 {
		s += int(r.ContentLength)
	}
	return s
}