Skip to content

Commit 0859bb8

Browse files
authored
Merge pull request #1152 from jessicalins/update-to-custom-reg
Update examples to use custom registry
2 parents 10b0550 + a340ca4 commit 0859bb8

File tree

3 files changed

+82
-50
lines changed

3 files changed

+82
-50
lines changed

examples/random/main.go

Lines changed: 40 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -30,45 +30,57 @@ import (
3030
"github.com/prometheus/client_golang/prometheus/promhttp"
3131
)
3232

33-
func main() {
34-
var (
35-
addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.")
36-
uniformDomain = flag.Float64("uniform.domain", 0.0002, "The domain for the uniform distribution.")
37-
normDomain = flag.Float64("normal.domain", 0.0002, "The domain for the normal distribution.")
38-
normMean = flag.Float64("normal.mean", 0.00001, "The mean for the normal distribution.")
39-
oscillationPeriod = flag.Duration("oscillation-period", 10*time.Minute, "The duration of the rate oscillation period.")
40-
)
41-
42-
flag.Parse()
33+
type metrics struct {
34+
rpcDurations *prometheus.SummaryVec
35+
rpcDurationsHistogram prometheus.Histogram
36+
}
4337

44-
var (
45-
// Create a summary to track fictional interservice RPC latencies for three
38+
func NewMetrics(reg prometheus.Registerer, normMean, normDomain float64) *metrics {
39+
m := &metrics{
40+
// Create a summary to track fictional inter service RPC latencies for three
4641
// distinct services with different latency distributions. These services are
4742
// differentiated via a "service" label.
48-
rpcDurations = prometheus.NewSummaryVec(
43+
rpcDurations: prometheus.NewSummaryVec(
4944
prometheus.SummaryOpts{
5045
Name: "rpc_durations_seconds",
5146
Help: "RPC latency distributions.",
5247
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
5348
},
5449
[]string{"service"},
55-
)
50+
),
5651
// The same as above, but now as a histogram, and only for the normal
5752
// distribution. The buckets are targeted to the parameters of the
5853
// normal distribution, with 20 buckets centered on the mean, each
5954
// half-sigma wide.
60-
rpcDurationsHistogram = prometheus.NewHistogram(prometheus.HistogramOpts{
55+
rpcDurationsHistogram: prometheus.NewHistogram(prometheus.HistogramOpts{
6156
Name: "rpc_durations_histogram_seconds",
6257
Help: "RPC latency distributions.",
63-
Buckets: prometheus.LinearBuckets(*normMean-5**normDomain, .5**normDomain, 20),
64-
})
58+
Buckets: prometheus.LinearBuckets(normMean-5*normDomain, .5*normDomain, 20),
59+
}),
60+
}
61+
reg.MustRegister(m.rpcDurations)
62+
reg.MustRegister(m.rpcDurationsHistogram)
63+
return m
64+
}
65+
66+
func main() {
67+
var (
68+
addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.")
69+
uniformDomain = flag.Float64("uniform.domain", 0.0002, "The domain for the uniform distribution.")
70+
normDomain = flag.Float64("normal.domain", 0.0002, "The domain for the normal distribution.")
71+
normMean = flag.Float64("normal.mean", 0.00001, "The mean for the normal distribution.")
72+
oscillationPeriod = flag.Duration("oscillation-period", 10*time.Minute, "The duration of the rate oscillation period.")
6573
)
6674

67-
// Register the summary and the histogram with Prometheus's default registry.
68-
prometheus.MustRegister(rpcDurations)
69-
prometheus.MustRegister(rpcDurationsHistogram)
75+
flag.Parse()
76+
77+
// Create a non-global registry.
78+
reg := prometheus.NewRegistry()
79+
80+
// Create new metrics and register them using the custom registry.
81+
m := NewMetrics(reg, *normMean, *normDomain)
7082
// Add Go module build info.
71-
prometheus.MustRegister(collectors.NewBuildInfoCollector())
83+
reg.MustRegister(collectors.NewBuildInfoCollector())
7284

7385
start := time.Now()
7486

@@ -80,22 +92,22 @@ func main() {
8092
go func() {
8193
for {
8294
v := rand.Float64() * *uniformDomain
83-
rpcDurations.WithLabelValues("uniform").Observe(v)
95+
m.rpcDurations.WithLabelValues("uniform").Observe(v)
8496
time.Sleep(time.Duration(100*oscillationFactor()) * time.Millisecond)
8597
}
8698
}()
8799

88100
go func() {
89101
for {
90102
v := (rand.NormFloat64() * *normDomain) + *normMean
91-
rpcDurations.WithLabelValues("normal").Observe(v)
103+
m.rpcDurations.WithLabelValues("normal").Observe(v)
92104
// Demonstrate exemplar support with a dummy ID. This
93105
// would be something like a trace ID in a real
94106
// application. Note the necessary type assertion. We
95107
// already know that rpcDurationsHistogram implements
96108
// the ExemplarObserver interface and thus don't need to
97109
// check the outcome of the type assertion.
98-
rpcDurationsHistogram.(prometheus.ExemplarObserver).ObserveWithExemplar(
110+
m.rpcDurationsHistogram.(prometheus.ExemplarObserver).ObserveWithExemplar(
99111
v, prometheus.Labels{"dummyID": fmt.Sprint(rand.Intn(100000))},
100112
)
101113
time.Sleep(time.Duration(75*oscillationFactor()) * time.Millisecond)
@@ -105,17 +117,19 @@ func main() {
105117
go func() {
106118
for {
107119
v := rand.ExpFloat64() / 1e6
108-
rpcDurations.WithLabelValues("exponential").Observe(v)
120+
m.rpcDurations.WithLabelValues("exponential").Observe(v)
109121
time.Sleep(time.Duration(50*oscillationFactor()) * time.Millisecond)
110122
}
111123
}()
112124

113125
// Expose the registered metrics via HTTP.
114126
http.Handle("/metrics", promhttp.HandlerFor(
115-
prometheus.DefaultGatherer,
127+
reg,
116128
promhttp.HandlerOpts{
117129
// Opt into OpenMetrics to support exemplars.
118130
EnableOpenMetrics: true,
131+
// Pass custom registry
132+
Registry: reg,
119133
},
120134
))
121135
log.Fatal(http.ListenAndServe(*addr, nil))

examples/simple/main.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,19 @@ import (
1919
"log"
2020
"net/http"
2121

22+
"github.com/prometheus/client_golang/prometheus"
2223
"github.com/prometheus/client_golang/prometheus/promhttp"
2324
)
2425

2526
var addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.")
2627

2728
func main() {
2829
flag.Parse()
29-
http.Handle("/metrics", promhttp.Handler())
30+
31+
// Create non-global registry.
32+
reg := prometheus.NewRegistry()
33+
34+
// Expose /metrics HTTP endpoint using the created custom registry.
35+
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{Registry: reg}))
3036
log.Fatal(http.ListenAndServe(*addr, nil))
3137
}

prometheus/doc.go

Lines changed: 35 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -35,39 +35,51 @@
3535
// "github.com/prometheus/client_golang/prometheus/promhttp"
3636
// )
3737
//
38-
// var (
39-
// cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
40-
// Name: "cpu_temperature_celsius",
41-
// Help: "Current temperature of the CPU.",
42-
// })
43-
// hdFailures = prometheus.NewCounterVec(
44-
// prometheus.CounterOpts{
45-
// Name: "hd_errors_total",
46-
// Help: "Number of hard-disk errors.",
47-
// },
48-
// []string{"device"},
49-
// )
50-
// )
38+
// type metrics struct {
39+
// cpuTemp prometheus.Gauge
40+
// hdFailures *prometheus.CounterVec
41+
// }
5142
//
52-
// func init() {
53-
// // Metrics have to be registered to be exposed:
54-
// prometheus.MustRegister(cpuTemp)
55-
// prometheus.MustRegister(hdFailures)
43+
// func NewMetrics(reg prometheus.Registerer) *metrics {
44+
// m := &metrics{
45+
// cpuTemp: prometheus.NewGauge(prometheus.GaugeOpts{
46+
// Name: "cpu_temperature_celsius",
47+
// Help: "Current temperature of the CPU.",
48+
// }),
49+
// hdFailures: prometheus.NewCounterVec(
50+
// prometheus.CounterOpts{
51+
// Name: "hd_errors_total",
52+
// Help: "Number of hard-disk errors.",
53+
// },
54+
// []string{"device"},
55+
// ),
56+
// }
57+
// reg.MustRegister(m.cpuTemp)
58+
// reg.MustRegister(m.hdFailures)
59+
// return m
5660
// }
5761
//
5862
// func main() {
59-
// cpuTemp.Set(65.3)
60-
// hdFailures.With(prometheus.Labels{"device":"/dev/sda"}).Inc()
61-
//
62-
// // The Handler function provides a default handler to expose metrics
63-
// // via an HTTP server. "/metrics" is the usual endpoint for that.
64-
// http.Handle("/metrics", promhttp.Handler())
63+
// // Create a non-global registry.
64+
// reg := prometheus.NewRegistry()
65+
//
66+
// // Create new metrics and register them using the custom registry.
67+
// m := NewMetrics(reg)
68+
// // Set values for the new created metrics.
69+
// m.cpuTemp.Set(65.3)
70+
// m.hdFailures.With(prometheus.Labels{"device":"/dev/sda"}).Inc()
71+
//
72+
// // Expose metrics and custom registry via an HTTP server
73+
// // using the HandleFor function. "/metrics" is the usual endpoint for that.
74+
// http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{Registry: reg}))
6575
// log.Fatal(http.ListenAndServe(":8080", nil))
6676
// }
6777
//
6878
//
6979
// This is a complete program that exports two metrics, a Gauge and a Counter,
7080
// the latter with a label attached to turn it into a (one-dimensional) vector.
81+
// It register the metrics using a custom registry and exposes them via an HTTP server
82+
// on the /metrics endpoint.
7183
//
7284
// Metrics
7385
//

0 commit comments

Comments
 (0)