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 }
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. // ... }