コード例 #1
0
func ExampleTimer_gauge() error {
	// The Set method of the Gauge is used to observe the duration.
	timer := prometheus.NewTimer(prometheus.ObserverFunc(funcDuration.Set))
	defer timer.ObserveDuration()

	// Do something. Return errors as encountered. The use of 'defer' above
	// makes sure the function is still timed properly.
	return nil
}
コード例 #2
0
func ExampleTimer() {
	// timer times this example function. It uses a Histogram, but a Summary
	// would also work, as both implement Observer. Check out
	// https://prometheus.io/docs/practices/histograms/ for differences.
	timer := prometheus.NewTimer(requestDuration)
	defer timer.ObserveDuration()

	// Do something here that takes time.
	time.Sleep(time.Duration(rand.NormFloat64()*10000+50000) * time.Microsecond)
}
コード例 #3
0
func handler(w http.ResponseWriter, r *http.Request) {
	status := http.StatusOK
	// The ObserverFunc gets called by the deferred ObserveDuration and
	// decides wich Histogram's Observe method is called.
	timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
		switch {
		case status >= 500: // Server error.
			apiRequestDuration.WithLabelValues("5xx").Observe(v)
		case status >= 400: // Client error.
			apiRequestDuration.WithLabelValues("4xx").Observe(v)
		case status >= 300: // Redirection.
			apiRequestDuration.WithLabelValues("3xx").Observe(v)
		case status >= 200: // Success.
			apiRequestDuration.WithLabelValues("2xx").Observe(v)
		default: // Informational.
			apiRequestDuration.WithLabelValues("1xx").Observe(v)
		}
	}))
	defer timer.ObserveDuration()

	// Handle the request. Set status accordingly.
	// ...
}