generated from fun-stack/example
-
Notifications
You must be signed in to change notification settings - Fork 4
/
prometheus.go
61 lines (46 loc) · 1.65 KB
/
prometheus.go
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
package main
import (
"context"
"net/http"
"os"
"time"
"github.com/VictoriaMetrics/metrics"
"github.com/johnwarden/httperror"
"golang.org/x/exp/slog"
)
// Register various metrics.
// Metric name may contain labels in Prometheus format - see below.
var (
crawlErrorsTotal = metrics.NewCounter(`errors_total{type="crawl"}`)
requestErrorsTotal = metrics.NewCounter(`errors_total{type="request"}`)
crawlDuration = metrics.NewHistogram("crawl_duration_seconds")
crawlPostprocessingDuration = metrics.NewHistogram("crawl_postprocessing_duration_seconds")
upvotesTotal = metrics.NewCounter(`upvotes_total`)
submissionsTotal = metrics.NewCounter(`submissions_total`)
)
func servePrometheusMetrics() func(ctx context.Context) error {
mux := http.NewServeMux()
// Export all the registered metrics in Prometheus format at `/metrics` http path.
mux.HandleFunc("/metrics", func(w http.ResponseWriter, req *http.Request) {
metrics.WritePrometheus(w, true)
})
listenAddress := os.Getenv("LISTEN_ADDRESS")
s := &http.Server{
Addr: listenAddress + ":9091",
Handler: mux,
}
go func() {
LogFatal(slog.Default(), "Listen and serve prometheus", s.ListenAndServe())
}()
return s.Shutdown
}
func prometheusMiddleware[P any](routeName string, h httperror.XHandler[P]) httperror.XHandlerFunc[P] {
// Register summary with a single label.
requestDuration := metrics.NewHistogram(`requests_duration_seconds{route="` + routeName + `"}`)
return func(w http.ResponseWriter, r *http.Request, p P) error {
startTime := time.Now()
defer requestDuration.UpdateDuration(startTime)
err := h.Serve(w, r, p)
return err
}
}