Debian Codegraph @

prometheus/example_timer_complex_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 "net/http"
18
19 "github.com/prometheus/client_golang/prometheus"
20 )
21
22 // apiRequestDuration tracks the duration separate for each HTTP status
23 // class (1xx, 2xx, ...). This creates a fair amount of time series on
24 // the Prometheus server. Usually, you would track the duration of
25 // serving HTTP request without partitioning by outcome. Do something
26 // like this only if needed. Also note how only status classes are
27 // tracked, not every single status code. The latter would create an
28 // even larger amount of time series. Request counters partitioned by
29 // status code are usually OK as each counter only creates one time
30 // series. Histograms are way more expensive, so partition with care and
31 // only where you really need separate latency tracking. Partitioning by
32 // status class is only an example. In concrete cases, other partitions
33 // might make more sense.
34 var apiRequestDuration = prometheus.NewHistogramVec(
35 prometheus.HistogramOpts{
36 Name: "api_request_duration_seconds",
37 Help: "Histogram for the request duration of the public API, partitioned by status class.",
38 Buckets: prometheus.ExponentialBuckets(0.1, 1.5, 5),
39 },
40 []string{"status_class"},
41 )
42
43 func handler(w http.ResponseWriter, r *http.Request) {
44 status := http.StatusOK
45 // The ObserverFunc gets called by the deferred ObserveDuration and
46 // decides which Histogram's Observe method is called.
47 timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
48 switch {
49 case status >= 500: // Server error.
50 apiRequestDuration.WithLabelValues("5xx").Observe(v)
51 case status >= 400: // Client error.
52 apiRequestDuration.WithLabelValues("4xx").Observe(v)
53 case status >= 300: // Redirection.
54 apiRequestDuration.WithLabelValues("3xx").Observe(v)
55 case status >= 200: // Success.
56 apiRequestDuration.WithLabelValues("2xx").Observe(v)
57 default: // Informational.
58 apiRequestDuration.WithLabelValues("1xx").Observe(v)
59 }
60 }))
61 defer timer.ObserveDuration()
62
63 // Handle the request. Set status accordingly.
64 // ...
65 }
66
67 func ExampleTimer_complex() {
68 http.HandleFunc("/api", handler)
69 }