Skip to content

Commit

Permalink
Add HTTP metrics to prometheus
Browse files Browse the repository at this point in the history
  • Loading branch information
geertw committed Jun 28, 2022
1 parent bda45eb commit 45a96c0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
33 changes: 33 additions & 0 deletions api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,44 @@ import (
"encoding/json"
"net/http"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/rijdendetreinen/gotrain/stores"

"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)

var (
httpDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "gotrain",
Subsystem: "http",
Name: "duration",
Help: "Duration of HTTP requests.",
}, []string{"path"})
)

var (
httpReqs = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "gotrain",
Subsystem: "http",
Name: "requests",
Help: "HTTP requests",
}, []string{"path", "url"})
)

// prometheusMiddleware implements mux.MiddlewareFunc.
func prometheusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
timer := prometheus.NewTimer(httpDuration.WithLabelValues(path))
next.ServeHTTP(w, r)
timer.ObserveDuration()
httpReqs.WithLabelValues(path, r.URL.Path).Add(1)
})
}

// ServeAPI serves the REST API on the given address
func ServeAPI(address string, exit chan bool) {
srv := &http.Server{Addr: address}
Expand All @@ -33,6 +65,7 @@ func ServeAPI(address string, exit chan bool) {
router.HandleFunc("/v2/services/stats", serviceCounters).Methods("GET")
router.HandleFunc("/v2/services/service/{id}/{date}", serviceDetails).Methods("GET")

router.Use(prometheusMiddleware)
srv.Handler = router

go listenAndServe(srv, exit)
Expand Down
10 changes: 5 additions & 5 deletions cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,6 @@ func startServer(cmd *cobra.Command) {
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)

if viper.GetBool("prometheus.enabled") {
prometheus_interface.SetupPrometheus()
prometheus_interface.StartPrometheusInterface()
}

signalChan := make(chan os.Signal, 1)
shutdownFinished := make(chan struct{})

Expand All @@ -72,6 +67,11 @@ func startServer(cmd *cobra.Command) {
apiAddress := viper.GetString("api.address")
go api.ServeAPI(apiAddress, exitRestAPI)

if viper.GetBool("prometheus.enabled") {
prometheus_interface.SetupPrometheus()
prometheus_interface.StartPrometheusInterface()
}

setupCleanupScheduler()
setupDowntimeDetector()
setupAutoSave()
Expand Down

0 comments on commit 45a96c0

Please sign in to comment.