Debian Codegraph @

prometheus/example_timer_gauge_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 "os"
18
19 "github.com/prometheus/client_golang/prometheus"
20 )
21
22 // If a function is called rarely (i.e. not more often than scrapes
23 // happen) or ideally only once (like in a batch job), it can make sense
24 // to use a Gauge for timing the function call. For timing a batch job
25 // and pushing the result to a Pushgateway, see also the comprehensive
26 // example in the push package.
27 var funcDuration = prometheus.NewGauge(prometheus.GaugeOpts{
28 Name: "example_function_duration_seconds",
29 Help: "Duration of the last call of an example function.",
30 })
31
32 func run() error {
33 // The Set method of the Gauge is used to observe the duration.
34 timer := prometheus.NewTimer(prometheus.ObserverFunc(funcDuration.Set))
35 defer timer.ObserveDuration()
36
37 // Do something. Return errors as encountered. The use of 'defer' above
38 // makes sure the function is still timed properly.
39 return nil
40 }
41
42 func ExampleTimer_gauge() {
43 if err := run(); err != nil {
44 os.Exit(1)
45 }
46 }