Skip to content

Instantly share code, notes, and snippets.

@betandr
Last active February 5, 2019 17:04
Show Gist options
  • Save betandr/03e9aa227dc99a4c088cf6c499e60f90 to your computer and use it in GitHub Desktop.
Save betandr/03e9aa227dc99a4c088cf6c499e60f90 to your computer and use it in GitHub Desktop.
Prometheus example in Go
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
requestDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "request_duration_milliseconds",
Help: "Request duration distribution.",
Buckets: prometheus.LinearBuckets(0, 40, 5),
})
requests = promauto.NewCounter(
prometheus.CounterOpts{
Name: "requests_total",
Help: "The total number of requests",
})
)
func init() {
prometheus.MustRegister(requestDuration)
}
func main() {
handler := func(w http.ResponseWriter, r *http.Request) {
delay := rand.Intn(200)
requests.Inc() // increment counter
requestDuration.Observe(float64(delay)) // send metric
time.Sleep(time.Duration(delay) * time.Millisecond) // sleep for random
fmt.Fprintf(w, "Response in %d milliseconds", delay) // response
}
http.HandleFunc("/", handler)
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8000", nil))
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment