Skip to content

Instantly share code, notes, and snippets.

@takuhiro
Last active June 21, 2020 23:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takuhiro/03cd4c19fba5717e6387e73d0feafdd3 to your computer and use it in GitHub Desktop.
Save takuhiro/03cd4c19fba5717e6387e73d0feafdd3 to your computer and use it in GitHub Desktop.
Prometheus Instrumentation Sample
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
errorCount = prometheus.NewCounter(prometheus.CounterOpts{
Name: "greeting_error_count_total",
Help: "Counter of HTTP requests resulting in an error.",
})
successCount = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "greeting_success_count_total",
Help: "Counter of HTTP requests resulting in a success.",
}, []string{"type"})
requestCount = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http_request_count_total",
Help: "Counter of HTTP requests made.",
}, []string{"code", "method"})
requestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "A histogram of latencies for requests.",
Buckets: append([]float64{0.000001, 0.001, 0.003}, prometheus.DefBuckets...),
}, []string{"code", "method"})
responseSize = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_response_size_bytes",
Help: "A histogram of response sizes for requests.",
Buckets: []float64{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20},
}, []string{"code", "method"})
)
func init() {
prometheus.MustRegister(errorCount)
prometheus.MustRegister(successCount)
prometheus.MustRegister(requestCount)
prometheus.MustRegister(requestDuration)
prometheus.MustRegister(responseSize)
}
func main() {
helloHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rand.Seed(time.Now().UnixNano())
switch rand.Intn(4) {
case 0:
log.Println("Hello!")
successCount.WithLabelValues("hello").Inc()
fmt.Fprint(w, "Hello!")
case 1:
log.Println("Hi!")
successCount.WithLabelValues("hi").Inc()
fmt.Fprint(w, "Hi!")
case 2:
log.Println("Hey!")
successCount.WithLabelValues("hey").Inc()
fmt.Fprint(w, "Hey!")
case 3:
log.Println("Error!")
errorCount.Inc()
fmt.Fprint(w, "Error!!")
}
})
// Instrument helloHandler
wrappedHelloHandler := promhttp.InstrumentHandlerCounter(requestCount,
promhttp.InstrumentHandlerDuration(requestDuration,
promhttp.InstrumentHandlerResponseSize(responseSize, helloHandler),
),
)
http.Handle("/", wrappedHelloHandler)
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
}
@godwhoa
Copy link

godwhoa commented Jun 21, 2020

Sweet!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment