Skip to content

Commit fffb76c

Browse files
committed
Merge branch 'main' into sparsehistogram
2 parents e92a8c7 + 0859bb8 commit fffb76c

File tree

3 files changed

+82
-50
lines changed

3 files changed

+82
-50
lines changed

examples/random/main.go

+40-26
Original file line numberDiff line numberDiff line change
@@ -30,29 +30,24 @@ 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
5752
// normal distribution. The histogram features both conventional
5853
// buckets as well as sparse buckets, the latter needed for the
@@ -64,19 +59,36 @@ func main() {
6459
// buckets are always centered on zero, with a growth factor of
6560
// one bucket to the text of (at most) 1.1. (The precise factor
6661
// is 2^2^-3 = 1.0905077...)
67-
rpcDurationsHistogram = prometheus.NewHistogram(prometheus.HistogramOpts{
62+
rpcDurationsHistogram: prometheus.NewHistogram(prometheus.HistogramOpts{
6863
Name: "rpc_durations_histogram_seconds",
6964
Help: "RPC latency distributions.",
70-
Buckets: prometheus.LinearBuckets(*normMean-5**normDomain, .5**normDomain, 20),
65+
Buckets: prometheus.LinearBuckets(normMean-5*normDomain, .5*normDomain, 20),
7166
NativeHistogramBucketFactor: 1.1,
72-
})
67+
}),
68+
}
69+
reg.MustRegister(m.rpcDurations)
70+
reg.MustRegister(m.rpcDurationsHistogram)
71+
return m
72+
}
73+
74+
func main() {
75+
var (
76+
addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.")
77+
uniformDomain = flag.Float64("uniform.domain", 0.0002, "The domain for the uniform distribution.")
78+
normDomain = flag.Float64("normal.domain", 0.0002, "The domain for the normal distribution.")
79+
normMean = flag.Float64("normal.mean", 0.00001, "The mean for the normal distribution.")
80+
oscillationPeriod = flag.Duration("oscillation-period", 10*time.Minute, "The duration of the rate oscillation period.")
7381
)
7482

75-
// Register the summary and the histogram with Prometheus's default registry.
76-
prometheus.MustRegister(rpcDurations)
77-
prometheus.MustRegister(rpcDurationsHistogram)
83+
flag.Parse()
84+
85+
// Create a non-global registry.
86+
reg := prometheus.NewRegistry()
87+
88+
// Create new metrics and register them using the custom registry.
89+
m := NewMetrics(reg, *normMean, *normDomain)
7890
// Add Go module build info.
79-
prometheus.MustRegister(collectors.NewBuildInfoCollector())
91+
reg.MustRegister(collectors.NewBuildInfoCollector())
8092

8193
start := time.Now()
8294

@@ -88,22 +100,22 @@ func main() {
88100
go func() {
89101
for {
90102
v := rand.Float64() * *uniformDomain
91-
rpcDurations.WithLabelValues("uniform").Observe(v)
103+
m.rpcDurations.WithLabelValues("uniform").Observe(v)
92104
time.Sleep(time.Duration(100*oscillationFactor()) * time.Millisecond)
93105
}
94106
}()
95107

96108
go func() {
97109
for {
98110
v := (rand.NormFloat64() * *normDomain) + *normMean
99-
rpcDurations.WithLabelValues("normal").Observe(v)
111+
m.rpcDurations.WithLabelValues("normal").Observe(v)
100112
// Demonstrate exemplar support with a dummy ID. This
101113
// would be something like a trace ID in a real
102114
// application. Note the necessary type assertion. We
103115
// already know that rpcDurationsHistogram implements
104116
// the ExemplarObserver interface and thus don't need to
105117
// check the outcome of the type assertion.
106-
rpcDurationsHistogram.(prometheus.ExemplarObserver).ObserveWithExemplar(
118+
m.rpcDurationsHistogram.(prometheus.ExemplarObserver).ObserveWithExemplar(
107119
v, prometheus.Labels{"dummyID": fmt.Sprint(rand.Intn(100000))},
108120
)
109121
time.Sleep(time.Duration(75*oscillationFactor()) * time.Millisecond)
@@ -113,17 +125,19 @@ func main() {
113125
go func() {
114126
for {
115127
v := rand.ExpFloat64() / 1e6
116-
rpcDurations.WithLabelValues("exponential").Observe(v)
128+
m.rpcDurations.WithLabelValues("exponential").Observe(v)
117129
time.Sleep(time.Duration(50*oscillationFactor()) * time.Millisecond)
118130
}
119131
}()
120132

121133
// Expose the registered metrics via HTTP.
122134
http.Handle("/metrics", promhttp.HandlerFor(
123-
prometheus.DefaultGatherer,
135+
reg,
124136
promhttp.HandlerOpts{
125137
// Opt into OpenMetrics to support exemplars.
126138
EnableOpenMetrics: true,
139+
// Pass custom registry
140+
Registry: reg,
127141
},
128142
))
129143
log.Fatal(http.ListenAndServe(*addr, nil))

examples/simple/main.go

+7-1
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

+35-23
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)