Skip to content

Instantly share code, notes, and snippets.

@nevill
Created July 22, 2019 06:45
Show Gist options
  • Save nevill/9e18049cb6d33180e2040d3691cde326 to your computer and use it in GitHub Desktop.
Save nevill/9e18049cb6d33180e2040d3691cde326 to your computer and use it in GitHub Desktop.
Prometheus
package main
import (
"log"
"math/rand"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
httpReqs = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "user_http_requests_total",
Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
},
[]string{"code", "method"},
)
method = []string{"GET", "GET", "POST", "GET", "GET", "GET", "GET", "POST"}
code = []string{"503", "200", "200", "200", "200", "404", "200", "200"}
)
func init() {
// Metrics have to be registered to be exposed:
prometheus.MustRegister(httpReqs)
}
func generateRequest() <-chan [2]string {
ticker := time.NewTicker(2 * time.Second)
metrics := make(chan [2]string)
go func() {
for range ticker.C {
request := [2]string{
code[rand.Intn(len(code))],
method[rand.Intn(len(method))],
}
metrics <- request
}
}()
return metrics
}
func main() {
httpReqs.WithLabelValues("404", "POST").Add(42)
// m := httpReqs.withLabelValue("200", "GET")
metrics := generateRequest()
go func() {
for {
select {
case request := <-metrics:
httpReqs.WithLabelValues(request[0], request[1]).Inc()
log.Println(request)
}
}
}()
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment