forked from cloudflare/privacy-gateway-server-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprometheus_metrics.go
96 lines (81 loc) · 2.38 KB
/
prometheus_metrics.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
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
// Copyright (c) 2024 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
package main
import (
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type PrometheusConfig struct {
Host string
Port string
ScrapePath string
MetricName string
}
type PrometheusMetrics struct {
startedAt time.Time
histogram prometheus.ObserverVec
}
func (p *PrometheusMetrics) Fire(result string) {
observer := p.histogram.With(prometheus.Labels{
"method": "unknown",
"status": "unknown",
"result": result,
})
p.observe(observer)
}
func (p *PrometheusMetrics) ResponseStatus(method string, status int) {
observer := p.histogram.With(prometheus.Labels{
"method": method,
"status": fmt.Sprint(status),
"result": "unknown",
})
p.observe(observer)
}
func (p *PrometheusMetrics) observe(observer prometheus.Observer) {
elapsed := time.Now().Sub(p.startedAt)
observer.Observe(float64(elapsed.Milliseconds()))
}
type PrometheusMetricsFactory struct {
metricName string
}
func NewPrometheusMetricsFactory(config PrometheusConfig) (MetricsFactory, error) {
serveMux := http.NewServeMux()
serveMux.Handle(config.ScrapePath, promhttp.Handler())
server := http.Server{
Addr: net.JoinHostPort(config.Host, config.Port),
Handler: serveMux,
}
go func() {
slog.Debug("Listening for Prometheus scrapes", "host", config.Host, "port", config.Port)
slog.Error("Error serving Prometheus scrapes", "error", server.ListenAndServe())
os.Exit(1)
}()
return &PrometheusMetricsFactory{metricName: config.MetricName}, nil
}
func (p PrometheusMetricsFactory) Create(eventName string) Metrics {
histogram := prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: p.metricName,
}, []string{"eventName", "status", "method", "result"})
if err := prometheus.Register(histogram); err != nil {
are := &prometheus.AlreadyRegisteredError{}
if errors.As(err, are) {
// Use previously registered metric collector
histogram = are.ExistingCollector.(*prometheus.HistogramVec)
} else {
// There's no other reason prometheus.Register should fail and the interface won't let
// us return an error.
panic(err)
}
}
return &PrometheusMetrics{
startedAt: time.Now(),
histogram: histogram.MustCurryWith(prometheus.Labels{"eventName": eventName}),
}
}