all repos

onasty @ efd970430597e242aa15c24f868fc0e7103b45ac

a one-time notes service

onasty/internal/metrics/http_metrics.go(view raw)

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
package metrics

import (
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
)

var (
	successfulHTTPRequest = promauto.NewCounterVec(prometheus.CounterOpts{
		Name:        "http_successful_requests_total",
		Help:        "the total number of successful http requests",
		ConstLabels: map[string]string{"status": "success"},
	}, []string{"method", "uri"})

	failedHTTPRequest = promauto.NewCounterVec(prometheus.CounterOpts{
		Name:        "http_failed_requests_total",
		Help:        "the total number of failed http requests",
		ConstLabels: map[string]string{"status": "failure"},
	}, []string{"method", "uri"})

	latencyHTTPRequest = promauto.NewHistogramVec(prometheus.HistogramOpts{
		Name:    "http_request_latency_seconds",
		Help:    "the latency of http requests in seconds",
		Buckets: prometheus.DefBuckets,
	}, []string{"method", "uri"})
)

func RecordSuccessfulRequestMetric(method, uri string) {
	go successfulHTTPRequest.With(prometheus.Labels{
		"method": method,
		"uri":    uri,
	}).Inc()
}

func RecordFailedRequestMetric(method, uri string) {
	go failedHTTPRequest.With(prometheus.Labels{
		"method": method,
		"uri":    uri,
	}).Inc()
}

func RecordLatencyRequestMetric(method, uri string, latency time.Duration) {
	go latencyHTTPRequest.With(prometheus.Labels{
		"method": method,
		"uri":    uri,
	}).Observe(latency.Seconds())
}