Debian Codegraph @

prometheus/examples_test.go

raw
1 // Copyright 2014 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package prometheus_test
15
16 import (
17 "bytes"
18 "errors"
19 "fmt"
20 "math"
21 "net/http"
22 "runtime"
23 "strings"
24 "time"
25
26 dto "github.com/prometheus/client_model/go"
27 "github.com/prometheus/common/expfmt"
28 "github.com/prometheus/common/model"
29
30 "github.com/prometheus/client_golang/prometheus"
31 "github.com/prometheus/client_golang/prometheus/promauto"
32 "github.com/prometheus/client_golang/prometheus/promhttp"
33 )
34
35 func ExampleGauge() {
36 opsQueued := prometheus.NewGauge(prometheus.GaugeOpts{
37 Namespace: "our_company",
38 Subsystem: "blob_storage",
39 Name: "ops_queued",
40 Help: "Number of blob storage operations waiting to be processed.",
41 })
42 prometheus.MustRegister(opsQueued)
43
44 // 10 operations queued by the goroutine managing incoming requests.
45 opsQueued.Add(10)
46 // A worker goroutine has picked up a waiting operation.
47 opsQueued.Dec()
48 // And once more...
49 opsQueued.Dec()
50 }
51
52 func ExampleGaugeVec() {
53 opsQueued := prometheus.NewGaugeVec(
54 prometheus.GaugeOpts{
55 Namespace: "our_company",
56 Subsystem: "blob_storage",
57 Name: "ops_queued",
58 Help: "Number of blob storage operations waiting to be processed, partitioned by user and type.",
59 },
60 []string{
61 // Which user has requested the operation?
62 "user",
63 // Of what type is the operation?
64 "type",
65 },
66 )
67 prometheus.MustRegister(opsQueued)
68
69 // Increase a value using compact (but order-sensitive!) WithLabelValues().
70 opsQueued.WithLabelValues("bob", "put").Add(4)
71 // Increase a value with a map using WithLabels. More verbose, but order
72 // doesn't matter anymore.
73 opsQueued.With(prometheus.Labels{"type": "delete", "user": "alice"}).Inc()
74 }
75
76 func ExampleGaugeFunc_simple() {
77 if err := prometheus.Register(prometheus.NewGaugeFunc(
78 prometheus.GaugeOpts{
79 Subsystem: "runtime",
80 Name: "goroutines_count",
81 Help: "Number of goroutines that currently exist.",
82 },
83 func() float64 { return float64(runtime.NumGoroutine()) },
84 )); err == nil {
85 fmt.Println("GaugeFunc 'goroutines_count' registered.")
86 }
87 // Note that the count of goroutines is a gauge (and not a counter) as
88 // it can go up and down.
89
90 // Output:
91 // GaugeFunc 'goroutines_count' registered.
92 }
93
94 func ExampleGaugeFunc_constLabels() {
95 // primaryDB and secondaryDB represent two example *sql.DB connections we want to instrument.
96 var primaryDB, secondaryDB interface {
97 Stats() struct{ OpenConnections int }
98 }
99
100 if err := prometheus.Register(prometheus.NewGaugeFunc(
101 prometheus.GaugeOpts{
102 Namespace: "mysql",
103 Name: "connections_open",
104 Help: "Number of mysql connections open.",
105 ConstLabels: prometheus.Labels{"destination": "primary"},
106 },
107 func() float64 { return float64(primaryDB.Stats().OpenConnections) },
108 )); err == nil {
109 fmt.Println(`GaugeFunc 'connections_open' for primary DB connection registered with labels {destination="primary"}`)
110 }
111
112 if err := prometheus.Register(prometheus.NewGaugeFunc(
113 prometheus.GaugeOpts{
114 Namespace: "mysql",
115 Name: "connections_open",
116 Help: "Number of mysql connections open.",
117 ConstLabels: prometheus.Labels{"destination": "secondary"},
118 },
119 func() float64 { return float64(secondaryDB.Stats().OpenConnections) },
120 )); err == nil {
121 fmt.Println(`GaugeFunc 'connections_open' for secondary DB connection registered with labels {destination="secondary"}`)
122 }
123
124 // Note that we can register more than once GaugeFunc with same metric name
125 // as long as their const labels are consistent.
126
127 // Output:
128 // GaugeFunc 'connections_open' for primary DB connection registered with labels {destination="primary"}
129 // GaugeFunc 'connections_open' for secondary DB connection registered with labels {destination="secondary"}
130 }
131
132 func ExampleCounterVec() {
133 httpReqs := prometheus.NewCounterVec(
134 prometheus.CounterOpts{
135 Name: "http_requests_total",
136 Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
137 },
138 []string{"code", "method"},
139 )
140 prometheus.MustRegister(httpReqs)
141
142 httpReqs.WithLabelValues("404", "POST").Add(42)
143
144 // If you have to access the same set of labels very frequently, it
145 // might be good to retrieve the metric only once and keep a handle to
146 // it. But beware of deletion of that metric, see below!
147 m := httpReqs.WithLabelValues("200", "GET")
148 for i := 0; i < 1000000; i++ {
149 m.Inc()
150 }
151 // Delete a metric from the vector. If you have previously kept a handle
152 // to that metric (as above), future updates via that handle will go
153 // unseen (even if you re-create a metric with the same label set
154 // later).
155 httpReqs.DeleteLabelValues("200", "GET")
156 // Same thing with the more verbose Labels syntax.
157 httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"})
158
159 // Just for demonstration, let's check the state of the counter vector
160 // by registering it with a custom registry and then let it collect the
161 // metrics.
162 reg := prometheus.NewRegistry()
163 reg.MustRegister(httpReqs)
164
165 metricFamilies, err := reg.Gather()
166 if err != nil || len(metricFamilies) != 1 {
167 panic("unexpected behavior of custom test registry")
168 }
169
170 fmt.Println(toNormalizedJSON(sanitizeMetricFamily(metricFamilies[0])))
171
172 // Output:
173 // {"name":"http_requests_total","help":"How many HTTP requests processed, partitioned by status code and HTTP method.","type":"COUNTER","metric":[{"label":[{"name":"code","value":"404"},{"name":"method","value":"POST"}],"counter":{"value":42,"createdTimestamp":"1970-01-01T00:00:10Z"}}]}
174 }
175
176 func ExampleRegister() {
177 // Imagine you have a worker pool and want to count the tasks completed.
178 taskCounter := prometheus.NewCounter(prometheus.CounterOpts{
179 Subsystem: "worker_pool",
180 Name: "completed_tasks_total",
181 Help: "Total number of tasks completed.",
182 })
183 // This will register fine.
184 if err := prometheus.Register(taskCounter); err != nil {
185 fmt.Println(err)
186 } else {
187 fmt.Println("taskCounter registered.")
188 }
189 // Don't forget to tell the HTTP server about the Prometheus handler.
190 // (In a real program, you still need to start the HTTP server...)
191 http.Handle("/metrics", promhttp.Handler())
192
193 // Now you can start workers and give every one of them a pointer to
194 // taskCounter and let it increment it whenever it completes a task.
195 taskCounter.Inc() // This has to happen somewhere in the worker code.
196
197 // But wait, you want to see how individual workers perform. So you need
198 // a vector of counters, with one element for each worker.
199 taskCounterVec := prometheus.NewCounterVec(
200 prometheus.CounterOpts{
201 Subsystem: "worker_pool",
202 Name: "completed_tasks_total",
203 Help: "Total number of tasks completed.",
204 },
205 []string{"worker_id"},
206 )
207
208 // Registering will fail because we already have a metric of that name.
209 if err := prometheus.Register(taskCounterVec); err != nil {
210 fmt.Println("taskCounterVec not registered:", err)
211 } else {
212 fmt.Println("taskCounterVec registered.")
213 }
214
215 // To fix, first unregister the old taskCounter.
216 if prometheus.Unregister(taskCounter) {
217 fmt.Println("taskCounter unregistered.")
218 }
219
220 // Try registering taskCounterVec again.
221 if err := prometheus.Register(taskCounterVec); err != nil {
222 fmt.Println("taskCounterVec not registered:", err)
223 } else {
224 fmt.Println("taskCounterVec registered.")
225 }
226 // Bummer! Still doesn't work.
227
228 // Prometheus will not allow you to ever export metrics with
229 // inconsistent help strings or label names. After unregistering, the
230 // unregistered metrics will cease to show up in the /metrics HTTP
231 // response, but the registry still remembers that those metrics had
232 // been exported before. For this example, we will now choose a
233 // different name. (In a real program, you would obviously not export
234 // the obsolete metric in the first place.)
235 taskCounterVec = prometheus.NewCounterVec(
236 prometheus.CounterOpts{
237 Subsystem: "worker_pool",
238 Name: "completed_tasks_by_id",
239 Help: "Total number of tasks completed.",
240 },
241 []string{"worker_id"},
242 )
243 if err := prometheus.Register(taskCounterVec); err != nil {
244 fmt.Println("taskCounterVec not registered:", err)
245 } else {
246 fmt.Println("taskCounterVec registered.")
247 }
248 // Finally it worked!
249
250 // The workers have to tell taskCounterVec their id to increment the
251 // right element in the metric vector.
252 taskCounterVec.WithLabelValues("42").Inc() // Code from worker 42.
253
254 // Each worker could also keep a reference to their own counter element
255 // around. Pick the counter at initialization time of the worker.
256 myCounter := taskCounterVec.WithLabelValues("42") // From worker 42 initialization code.
257 myCounter.Inc() // Somewhere in the code of that worker.
258
259 // Note that something like WithLabelValues("42", "spurious arg") would
260 // panic (because you have provided too many label values). If you want
261 // to get an error instead, use GetMetricWithLabelValues(...) instead.
262 notMyCounter, err := taskCounterVec.GetMetricWithLabelValues("42", "spurious arg")
263 if err != nil {
264 fmt.Println("Worker initialization failed:", err)
265 }
266 if notMyCounter == nil {
267 fmt.Println("notMyCounter is nil.")
268 }
269
270 // A different (and somewhat tricky) approach is to use
271 // ConstLabels. ConstLabels are pairs of label names and label values
272 // that never change. Each worker creates and registers an own Counter
273 // instance where the only difference is in the value of the
274 // ConstLabels. Those Counters can all be registered because the
275 // different ConstLabel values guarantee that each worker will increment
276 // a different Counter metric.
277 counterOpts := prometheus.CounterOpts{
278 Subsystem: "worker_pool",
279 Name: "completed_tasks",
280 Help: "Total number of tasks completed.",
281 ConstLabels: prometheus.Labels{"worker_id": "42"},
282 }
283 taskCounterForWorker42 := prometheus.NewCounter(counterOpts)
284 if err := prometheus.Register(taskCounterForWorker42); err != nil {
285 fmt.Println("taskCounterVForWorker42 not registered:", err)
286 } else {
287 fmt.Println("taskCounterForWorker42 registered.")
288 }
289 // Obviously, in real code, taskCounterForWorker42 would be a member
290 // variable of a worker struct, and the "42" would be retrieved with a
291 // GetId() method or something. The Counter would be created and
292 // registered in the initialization code of the worker.
293
294 // For the creation of the next Counter, we can recycle
295 // counterOpts. Just change the ConstLabels.
296 counterOpts.ConstLabels = prometheus.Labels{"worker_id": "2001"}
297 taskCounterForWorker2001 := prometheus.NewCounter(counterOpts)
298 if err := prometheus.Register(taskCounterForWorker2001); err != nil {
299 fmt.Println("taskCounterVForWorker2001 not registered:", err)
300 } else {
301 fmt.Println("taskCounterForWorker2001 registered.")
302 }
303
304 taskCounterForWorker2001.Inc()
305 taskCounterForWorker42.Inc()
306 taskCounterForWorker2001.Inc()
307
308 // Yet another approach would be to turn the workers themselves into
309 // Collectors and register them. See the Collector example for details.
310
311 // Output:
312 // taskCounter registered.
313 // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: {worker_id}} has different label names or a different help string
314 // taskCounter unregistered.
315 // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: {worker_id}} has different label names or a different help string
316 // taskCounterVec registered.
317 // Worker initialization failed: inconsistent label cardinality: expected 1 label values but got 2 in []string{"42", "spurious arg"}
318 // notMyCounter is nil.
319 // taskCounterForWorker42 registered.
320 // taskCounterForWorker2001 registered.
321 }
322
323 func ExampleSummary() {
324 temps := prometheus.NewSummary(prometheus.SummaryOpts{
325 Name: "pond_temperature_celsius",
326 Help: "The temperature of the frog pond.",
327 Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
328 })
329
330 // Simulate some observations.
331 for i := 0; i < 1000; i++ {
332 temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10)
333 }
334
335 // Just for demonstration, let's check the state of the summary by
336 // (ab)using its Write method (which is usually only used by Prometheus
337 // internally).
338 metric := &dto.Metric{}
339 temps.Write(metric)
340
341 fmt.Println(toNormalizedJSON(sanitizeMetric(metric)))
342
343 // Output:
344 // {"summary":{"sampleCount":"1000","sampleSum":29969.50000000001,"quantile":[{"quantile":0.5,"value":31.1},{"quantile":0.9,"value":41.3},{"quantile":0.99,"value":41.9}],"createdTimestamp":"1970-01-01T00:00:10Z"}}
345 }
346
347 func ExampleSummaryVec() {
348 temps := prometheus.NewSummaryVec(
349 prometheus.SummaryOpts{
350 Name: "pond_temperature_celsius",
351 Help: "The temperature of the frog pond.",
352 Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
353 },
354 []string{"species"},
355 )
356
357 // Simulate some observations.
358 for i := 0; i < 1000; i++ {
359 temps.WithLabelValues("litoria-caerulea").Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10)
360 temps.WithLabelValues("lithobates-catesbeianus").Observe(32 + math.Floor(100*math.Cos(float64(i)*0.11))/10)
361 }
362
363 // Create a Summary without any observations.
364 temps.WithLabelValues("leiopelma-hochstetteri")
365
366 // Just for demonstration, let's check the state of the summary vector
367 // by registering it with a custom registry and then let it collect the
368 // metrics.
369 reg := prometheus.NewRegistry()
370 reg.MustRegister(temps)
371
372 metricFamilies, err := reg.Gather()
373 if err != nil || len(metricFamilies) != 1 {
374 panic("unexpected behavior of custom test registry")
375 }
376
377 fmt.Println(toNormalizedJSON(sanitizeMetricFamily(metricFamilies[0])))
378
379 // Output:
380 // {"name":"pond_temperature_celsius","help":"The temperature of the frog pond.","type":"SUMMARY","metric":[{"label":[{"name":"species","value":"leiopelma-hochstetteri"}],"summary":{"sampleCount":"0","sampleSum":0,"quantile":[{"quantile":0.5,"value":"NaN"},{"quantile":0.9,"value":"NaN"},{"quantile":0.99,"value":"NaN"}],"createdTimestamp":"1970-01-01T00:00:10Z"}},{"label":[{"name":"species","value":"lithobates-catesbeianus"}],"summary":{"sampleCount":"1000","sampleSum":31956.100000000017,"quantile":[{"quantile":0.5,"value":32.4},{"quantile":0.9,"value":41.4},{"quantile":0.99,"value":41.9}],"createdTimestamp":"1970-01-01T00:00:10Z"}},{"label":[{"name":"species","value":"litoria-caerulea"}],"summary":{"sampleCount":"1000","sampleSum":29969.50000000001,"quantile":[{"quantile":0.5,"value":31.1},{"quantile":0.9,"value":41.3},{"quantile":0.99,"value":41.9}],"createdTimestamp":"1970-01-01T00:00:10Z"}}]}
381 }
382
383 func ExampleNewConstSummary() {
384 desc := prometheus.NewDesc(
385 "http_request_duration_seconds",
386 "A summary of the HTTP request durations.",
387 []string{"code", "method"},
388 prometheus.Labels{"owner": "example"},
389 )
390
391 // Create a constant summary from values we got from a 3rd party telemetry system.
392 s := prometheus.MustNewConstSummary(
393 desc,
394 4711, 403.34,
395 map[float64]float64{0.5: 42.3, 0.9: 323.3},
396 "200", "get",
397 )
398
399 // Just for demonstration, let's check the state of the summary by
400 // (ab)using its Write method (which is usually only used by Prometheus
401 // internally).
402 metric := &dto.Metric{}
403 s.Write(metric)
404 fmt.Println(toNormalizedJSON(metric))
405
406 // Output:
407 // {"label":[{"name":"code","value":"200"},{"name":"method","value":"get"},{"name":"owner","value":"example"}],"summary":{"sampleCount":"4711","sampleSum":403.34,"quantile":[{"quantile":0.5,"value":42.3},{"quantile":0.9,"value":323.3}]}}
408 }
409
410 func ExampleNewConstSummaryWithCreatedTimestamp() {
411 desc := prometheus.NewDesc(
412 "http_request_duration_seconds",
413 "A summary of the HTTP request durations.",
414 []string{"code", "method"},
415 prometheus.Labels{"owner": "example"},
416 )
417
418 // Create a constant summary with created timestamp set
419 createdTs := time.Unix(1719670764, 123)
420 s := prometheus.MustNewConstSummaryWithCreatedTimestamp(
421 desc,
422 4711, 403.34,
423 map[float64]float64{0.5: 42.3, 0.9: 323.3},
424 createdTs,
425 "200", "get",
426 )
427
428 // Just for demonstration, let's check the state of the summary by
429 // (ab)using its Write method (which is usually only used by Prometheus
430 // internally).
431 metric := &dto.Metric{}
432 s.Write(metric)
433 fmt.Println(toNormalizedJSON(metric))
434
435 // Output:
436 // {"label":[{"name":"code","value":"200"},{"name":"method","value":"get"},{"name":"owner","value":"example"}],"summary":{"sampleCount":"4711","sampleSum":403.34,"quantile":[{"quantile":0.5,"value":42.3},{"quantile":0.9,"value":323.3}],"createdTimestamp":"2024-06-29T14:19:24.000000123Z"}}
437 }
438
439 func ExampleHistogram() {
440 temps := prometheus.NewHistogram(prometheus.HistogramOpts{
441 Name: "pond_temperature_celsius",
442 Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells.
443 Buckets: prometheus.LinearBuckets(20, 5, 5), // 5 buckets, each 5 centigrade wide.
444 })
445
446 // Simulate some observations.
447 for i := 0; i < 1000; i++ {
448 temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10)
449 }
450
451 // Just for demonstration, let's check the state of the histogram by
452 // (ab)using its Write method (which is usually only used by Prometheus
453 // internally).
454 metric := &dto.Metric{}
455 temps.Write(metric)
456
457 fmt.Println(toNormalizedJSON(sanitizeMetric(metric)))
458
459 // Output:
460 // {"histogram":{"sampleCount":"1000","sampleSum":29969.50000000001,"bucket":[{"cumulativeCount":"192","upperBound":20},{"cumulativeCount":"366","upperBound":25},{"cumulativeCount":"501","upperBound":30},{"cumulativeCount":"638","upperBound":35},{"cumulativeCount":"816","upperBound":40}],"createdTimestamp":"1970-01-01T00:00:10Z"}}
461 }
462
463 func ExampleNewConstHistogram() {
464 desc := prometheus.NewDesc(
465 "http_request_duration_seconds",
466 "A histogram of the HTTP request durations.",
467 []string{"code", "method"},
468 prometheus.Labels{"owner": "example"},
469 )
470
471 // Create a constant histogram from values we got from a 3rd party telemetry system.
472 h := prometheus.MustNewConstHistogram(
473 desc,
474 4711, 403.34,
475 map[float64]uint64{25: 121, 50: 2403, 100: 3221, 200: 4233},
476 "200", "get",
477 )
478
479 // Just for demonstration, let's check the state of the histogram by
480 // (ab)using its Write method (which is usually only used by Prometheus
481 // internally).
482 metric := &dto.Metric{}
483 h.Write(metric)
484 fmt.Println(toNormalizedJSON(metric))
485
486 // Output:
487 // {"label":[{"name":"code","value":"200"},{"name":"method","value":"get"},{"name":"owner","value":"example"}],"histogram":{"sampleCount":"4711","sampleSum":403.34,"bucket":[{"cumulativeCount":"121","upperBound":25},{"cumulativeCount":"2403","upperBound":50},{"cumulativeCount":"3221","upperBound":100},{"cumulativeCount":"4233","upperBound":200}]}}
488 }
489
490 func ExampleNewConstHistogramWithCreatedTimestamp() {
491 desc := prometheus.NewDesc(
492 "http_request_duration_seconds",
493 "A histogram of the HTTP request durations.",
494 []string{"code", "method"},
495 prometheus.Labels{"owner": "example"},
496 )
497
498 createdTs := time.Unix(1719670764, 123)
499 h := prometheus.MustNewConstHistogramWithCreatedTimestamp(
500 desc,
501 4711, 403.34,
502 map[float64]uint64{25: 121, 50: 2403, 100: 3221, 200: 4233},
503 createdTs,
504 "200", "get",
505 )
506
507 // Just for demonstration, let's check the state of the histogram by
508 // (ab)using its Write method (which is usually only used by Prometheus
509 // internally).
510 metric := &dto.Metric{}
511 h.Write(metric)
512 fmt.Println(toNormalizedJSON(metric))
513
514 // Output:
515 // {"label":[{"name":"code","value":"200"},{"name":"method","value":"get"},{"name":"owner","value":"example"}],"histogram":{"sampleCount":"4711","sampleSum":403.34,"bucket":[{"cumulativeCount":"121","upperBound":25},{"cumulativeCount":"2403","upperBound":50},{"cumulativeCount":"3221","upperBound":100},{"cumulativeCount":"4233","upperBound":200}],"createdTimestamp":"2024-06-29T14:19:24.000000123Z"}}
516 }
517
518 func ExampleNewConstHistogram_withExemplar() {
519 desc := prometheus.NewDesc(
520 "http_request_duration_seconds",
521 "A histogram of the HTTP request durations.",
522 []string{"code", "method"},
523 prometheus.Labels{"owner": "example"},
524 )
525
526 // Create a constant histogram from values we got from a 3rd party telemetry system.
527 h := prometheus.MustNewConstHistogram(
528 desc,
529 4711, 403.34,
530 map[float64]uint64{25: 121, 50: 2403, 100: 3221, 200: 4233},
531 "200", "get",
532 )
533
534 // Wrap const histogram with exemplars for each bucket.
535 exemplarTs, _ := time.Parse(time.RFC850, "Monday, 02-Jan-06 15:04:05 GMT")
536 exemplarLabels := prometheus.Labels{"testName": "testVal"}
537 h = prometheus.MustNewMetricWithExemplars(
538 h,
539 prometheus.Exemplar{Labels: exemplarLabels, Timestamp: exemplarTs, Value: 24.0},
540 prometheus.Exemplar{Labels: exemplarLabels, Timestamp: exemplarTs, Value: 42.0},
541 prometheus.Exemplar{Labels: exemplarLabels, Timestamp: exemplarTs, Value: 89.0},
542 prometheus.Exemplar{Labels: exemplarLabels, Timestamp: exemplarTs, Value: 157.0},
543 )
544
545 // Just for demonstration, let's check the state of the histogram by
546 // (ab)using its Write method (which is usually only used by Prometheus
547 // internally).
548 metric := &dto.Metric{}
549 h.Write(metric)
550 fmt.Println(toNormalizedJSON(metric))
551
552 // Output:
553 // {"label":[{"name":"code","value":"200"},{"name":"method","value":"get"},{"name":"owner","value":"example"}],"histogram":{"sampleCount":"4711","sampleSum":403.34,"bucket":[{"cumulativeCount":"121","upperBound":25,"exemplar":{"label":[{"name":"testName","value":"testVal"}],"value":24,"timestamp":"2006-01-02T15:04:05Z"}},{"cumulativeCount":"2403","upperBound":50,"exemplar":{"label":[{"name":"testName","value":"testVal"}],"value":42,"timestamp":"2006-01-02T15:04:05Z"}},{"cumulativeCount":"3221","upperBound":100,"exemplar":{"label":[{"name":"testName","value":"testVal"}],"value":89,"timestamp":"2006-01-02T15:04:05Z"}},{"cumulativeCount":"4233","upperBound":200,"exemplar":{"label":[{"name":"testName","value":"testVal"}],"value":157,"timestamp":"2006-01-02T15:04:05Z"}}]}}
554 }
555
556 func ExampleAlreadyRegisteredError() {
557 reqCounter := prometheus.NewCounter(prometheus.CounterOpts{
558 Name: "requests_total",
559 Help: "The total number of requests served.",
560 })
561 if err := prometheus.Register(reqCounter); err != nil {
562 are := &prometheus.AlreadyRegisteredError{}
563 if errors.As(err, are) {
564 // A counter for that metric has been registered before.
565 // Use the old counter from now on.
566 reqCounter = are.ExistingCollector.(prometheus.Counter)
567 } else {
568 // Something else went wrong!
569 panic(err)
570 }
571 }
572 reqCounter.Inc()
573 }
574
575 func ExampleGatherers() {
576 reg := prometheus.NewRegistry()
577 temp := prometheus.NewGaugeVec(
578 prometheus.GaugeOpts{
579 Name: "temperature_kelvin",
580 Help: "Temperature in Kelvin.",
581 },
582 []string{"location"},
583 )
584 reg.MustRegister(temp)
585 temp.WithLabelValues("outside").Set(273.14)
586 temp.WithLabelValues("inside").Set(298.44)
587
588 parser := expfmt.NewTextParser(model.UTF8Validation)
589
590 text := `
591 # TYPE humidity_percent gauge
592 # HELP humidity_percent Humidity in %.
593 humidity_percent{location="outside"} 45.4
594 humidity_percent{location="inside"} 33.2
595 # TYPE temperature_kelvin gauge
596 # HELP temperature_kelvin Temperature in Kelvin.
597 temperature_kelvin{location="somewhere else"} 4.5
598 `
599
600 parseText := func() ([]*dto.MetricFamily, error) {
601 parsed, err := parser.TextToMetricFamilies(strings.NewReader(text))
602 if err != nil {
603 return nil, err
604 }
605 var result []*dto.MetricFamily
606 for _, mf := range parsed {
607 result = append(result, mf)
608 }
609 return result, nil
610 }
611
612 gatherers := prometheus.Gatherers{
613 reg,
614 prometheus.GathererFunc(parseText),
615 }
616
617 gathering, err := gatherers.Gather()
618 if err != nil {
619 fmt.Println(err)
620 }
621
622 out := &bytes.Buffer{}
623 for _, mf := range gathering {
624 if _, err := expfmt.MetricFamilyToText(out, mf); err != nil {
625 panic(err)
626 }
627 }
628 fmt.Print(out.String())
629 fmt.Println("----------")
630
631 // Note how the temperature_kelvin metric family has been merged from
632 // different sources. Now try
633 text = `
634 # TYPE humidity_percent gauge
635 # HELP humidity_percent Humidity in %.
636 humidity_percent{location="outside"} 45.4
637 humidity_percent{location="inside"} 33.2
638 # TYPE temperature_kelvin gauge
639 # HELP temperature_kelvin Temperature in Kelvin.
640 # Duplicate metric:
641 temperature_kelvin{location="outside"} 265.3
642 # Missing location label (note that this is undesirable but valid):
643 temperature_kelvin 4.5
644 `
645
646 gathering, err = gatherers.Gather()
647 if err != nil {
648 // We expect error collected metric "temperature_kelvin" { label:<name:"location" value:"outside" > gauge:<value:265.3 > } was collected before with the same name and label values
649 // We cannot assert it because of https://github.com/golang/protobuf/issues/1121
650 if strings.HasPrefix(err.Error(), `collected metric "temperature_kelvin" `) {
651 fmt.Println("Found duplicated metric `temperature_kelvin`")
652 } else {
653 fmt.Print(err)
654 }
655 }
656 // Note that still as many metrics as possible are returned:
657 out.Reset()
658 for _, mf := range gathering {
659 if _, err := expfmt.MetricFamilyToText(out, mf); err != nil {
660 panic(err)
661 }
662 }
663 fmt.Print(out.String())
664
665 // Output:
666 // # HELP humidity_percent Humidity in %.
667 // # TYPE humidity_percent gauge
668 // humidity_percent{location="inside"} 33.2
669 // humidity_percent{location="outside"} 45.4
670 // # HELP temperature_kelvin Temperature in Kelvin.
671 // # TYPE temperature_kelvin gauge
672 // temperature_kelvin{location="inside"} 298.44
673 // temperature_kelvin{location="outside"} 273.14
674 // temperature_kelvin{location="somewhere else"} 4.5
675 // ----------
676 // Found duplicated metric `temperature_kelvin`
677 // # HELP humidity_percent Humidity in %.
678 // # TYPE humidity_percent gauge
679 // humidity_percent{location="inside"} 33.2
680 // humidity_percent{location="outside"} 45.4
681 // # HELP temperature_kelvin Temperature in Kelvin.
682 // # TYPE temperature_kelvin gauge
683 // temperature_kelvin 4.5
684 // temperature_kelvin{location="inside"} 298.44
685 // temperature_kelvin{location="outside"} 273.14
686 }
687
688 func ExampleNewMetricWithTimestamp() {
689 desc := prometheus.NewDesc(
690 "temperature_kelvin",
691 "Current temperature in Kelvin.",
692 nil, nil,
693 )
694
695 // Create a constant gauge from values we got from an external
696 // temperature reporting system. Those values are reported with a slight
697 // delay, so we want to add the timestamp of the actual measurement.
698 temperatureReportedByExternalSystem := 298.15
699 timeReportedByExternalSystem := time.Date(2009, time.November, 10, 23, 0, 0, 12345678, time.UTC)
700 s := prometheus.NewMetricWithTimestamp(
701 timeReportedByExternalSystem,
702 prometheus.MustNewConstMetric(
703 desc, prometheus.GaugeValue, temperatureReportedByExternalSystem,
704 ),
705 )
706
707 // Just for demonstration, let's check the state of the gauge by
708 // (ab)using its Write method (which is usually only used by Prometheus
709 // internally).
710 metric := &dto.Metric{}
711 s.Write(metric)
712 fmt.Println(toNormalizedJSON(metric))
713
714 // Output:
715 // {"gauge":{"value":298.15},"timestampMs":"1257894000012"}
716 }
717
718 func ExampleNewConstMetricWithCreatedTimestamp() {
719 // Here we have a metric that is reported by an external system.
720 // Besides providing the value, the external system also provides the
721 // timestamp when the metric was created.
722 desc := prometheus.NewDesc(
723 "time_since_epoch_seconds",
724 "Current epoch time in seconds.",
725 nil, nil,
726 )
727
728 timeSinceEpochReportedByExternalSystem := time.Date(2009, time.November, 10, 23, 0, 0, 12345678, time.UTC)
729 epoch := time.Unix(0, 0).UTC()
730 s := prometheus.MustNewConstMetricWithCreatedTimestamp(
731 desc, prometheus.CounterValue, float64(timeSinceEpochReportedByExternalSystem.Unix()), epoch,
732 )
733
734 metric := &dto.Metric{}
735 s.Write(metric)
736 fmt.Println(toNormalizedJSON(metric))
737
738 // Output:
739 // {"counter":{"value":1257894000,"createdTimestamp":"1970-01-01T00:00:00Z"}}
740 }
741
742 // Using CollectorFunc that registers the metric info for the HTTP requests.
743 func ExampleCollectorFunc() {
744 desc := prometheus.NewDesc(
745 "http_requests_info",
746 "Information about the received HTTP requests.",
747 []string{"code", "method"},
748 nil,
749 )
750
751 // Example 1: 42 GET requests with 200 OK status code.
752 collector := prometheus.CollectorFunc(func(ch chan<- prometheus.Metric) {
753 ch <- prometheus.MustNewConstMetric(
754 desc,
755 prometheus.CounterValue, // Metric type: Counter
756 42, // Value
757 "200", // Label value: HTTP status code
758 "GET", // Label value: HTTP method
759 )
760
761 // Example 2: 15 POST requests with 404 Not Found status code.
762 ch <- prometheus.MustNewConstMetric(
763 desc,
764 prometheus.CounterValue,
765 15,
766 "404",
767 "POST",
768 )
769 })
770
771 prometheus.MustRegister(collector)
772
773 // Just for demonstration, let's check the state of the metric by registering
774 // it with a custom registry and then let it collect the metrics.
775
776 reg := prometheus.NewRegistry()
777 reg.MustRegister(collector)
778
779 metricFamilies, err := reg.Gather()
780 if err != nil || len(metricFamilies) != 1 {
781 panic("unexpected behavior of custom test registry")
782 }
783
784 fmt.Println(toNormalizedJSON(sanitizeMetricFamily(metricFamilies[0])))
785
786 // Output:
787 // {"name":"http_requests_info","help":"Information about the received HTTP requests.","type":"COUNTER","metric":[{"label":[{"name":"code","value":"200"},{"name":"method","value":"GET"}],"counter":{"value":42}},{"label":[{"name":"code","value":"404"},{"name":"method","value":"POST"}],"counter":{"value":15}}]}
788 }
789
790 // Using WrapCollectorWith to un-register metrics registered by a third party lib.
791 // newThirdPartyLibFoo illustrates a constructor from a third-party lib that does
792 // not expose any way to un-register metrics.
793 func ExampleWrapCollectorWith() {
794 reg := prometheus.NewRegistry()
795
796 // We want to create two instances of thirdPartyLibFoo, each one wrapped with
797 // its "instance" label.
798 firstReg := prometheus.NewRegistry()
799 _ = newThirdPartyLibFoo(firstReg)
800 firstCollector := prometheus.WrapCollectorWith(prometheus.Labels{"instance": "first"}, firstReg)
801 reg.MustRegister(firstCollector)
802
803 secondReg := prometheus.NewRegistry()
804 _ = newThirdPartyLibFoo(secondReg)
805 secondCollector := prometheus.WrapCollectorWith(prometheus.Labels{"instance": "second"}, secondReg)
806 reg.MustRegister(secondCollector)
807
808 // So far we have illustrated that we can create two instances of thirdPartyLibFoo,
809 // wrapping each one's metrics with some const label.
810 // This is something we could've achieved by doing:
811 // newThirdPartyLibFoo(prometheus.WrapRegistererWith(prometheus.Labels{"instance": "first"}, reg))
812 metricFamilies, err := reg.Gather()
813 if err != nil {
814 panic("unexpected behavior of registry")
815 }
816 fmt.Println("Both instances:")
817 fmt.Println(toNormalizedJSON(sanitizeMetricFamily(metricFamilies[0])))
818
819 // Now we want to unregister first Foo's metrics, and then register them again.
820 // This is not possible by passing a wrapped Registerer to newThirdPartyLibFoo,
821 // because we have already lost track of the registered Collectors,
822 // however since we've collected Foo's metrics in it's own Registry, and we have registered that
823 // as a specific Collector, we can now de-register them:
824 unregistered := reg.Unregister(firstCollector)
825 if !unregistered {
826 panic("unexpected behavior of registry")
827 }
828
829 metricFamilies, err = reg.Gather()
830 if err != nil {
831 panic("unexpected behavior of registry")
832 }
833 fmt.Println("First unregistered:")
834 fmt.Println(toNormalizedJSON(sanitizeMetricFamily(metricFamilies[0])))
835
836 // Now we can create another instance of Foo with {instance: "first"} label again.
837 firstRegAgain := prometheus.NewRegistry()
838 _ = newThirdPartyLibFoo(firstRegAgain)
839 firstCollectorAgain := prometheus.WrapCollectorWith(prometheus.Labels{"instance": "first"}, firstRegAgain)
840 reg.MustRegister(firstCollectorAgain)
841
842 metricFamilies, err = reg.Gather()
843 if err != nil {
844 panic("unexpected behavior of registry")
845 }
846 fmt.Println("Both again:")
847 fmt.Println(toNormalizedJSON(sanitizeMetricFamily(metricFamilies[0])))
848
849 // Output:
850 // Both instances:
851 // {"name":"foo","help":"Registered forever.","type":"GAUGE","metric":[{"label":[{"name":"instance","value":"first"}],"gauge":{"value":1}},{"label":[{"name":"instance","value":"second"}],"gauge":{"value":1}}]}
852 // First unregistered:
853 // {"name":"foo","help":"Registered forever.","type":"GAUGE","metric":[{"label":[{"name":"instance","value":"second"}],"gauge":{"value":1}}]}
854 // Both again:
855 // {"name":"foo","help":"Registered forever.","type":"GAUGE","metric":[{"label":[{"name":"instance","value":"first"}],"gauge":{"value":1}},{"label":[{"name":"instance","value":"second"}],"gauge":{"value":1}}]}
856 }
857
858 func newThirdPartyLibFoo(reg prometheus.Registerer) struct{} {
859 foo := struct{}{}
860 // Register the metrics of the third party lib.
861 c := promauto.With(reg).NewGauge(prometheus.GaugeOpts{
862 Name: "foo",
863 Help: "Registered forever.",
864 })
865 c.Set(1)
866 return foo
867 }