Files
goma-gateway/internal/metrics/prometheus.go

72 lines
1.8 KiB
Go
Raw Normal View History

2024-11-10 17:06:58 +01:00
/*
* Copyright 2024 Jonas Kaninda
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
2024-11-17 03:56:47 +01:00
package metrics
2024-11-10 17:06:58 +01:00
import (
"net/http"
"strconv"
2024-11-10 17:06:58 +01:00
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
type PrometheusRoute struct {
2024-11-17 03:56:47 +01:00
Name string
Path string
2024-11-10 17:06:58 +01:00
}
2024-11-17 03:56:47 +01:00
var TotalRequests = prometheus.NewCounterVec(
2024-11-10 17:06:58 +01:00
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Number of get requests.",
},
[]string{"name", "path"},
2024-11-10 17:06:58 +01:00
)
2024-11-17 03:56:47 +01:00
var ResponseStatus = prometheus.NewCounterVec(
2024-11-10 17:06:58 +01:00
prometheus.CounterOpts{
Name: "response_status",
Help: "Status of HTTP response",
},
[]string{"status"},
)
2024-11-17 03:56:47 +01:00
var HttpDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
2024-11-10 17:06:58 +01:00
Name: "http_response_time_seconds",
Help: "Duration of HTTP requests.",
}, []string{"name", "path"})
2024-11-10 17:06:58 +01:00
2024-11-17 03:56:47 +01:00
func (pr PrometheusRoute) PrometheusMiddleware(next http.Handler) http.Handler {
2024-11-10 17:06:58 +01:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2024-11-17 03:56:47 +01:00
path := pr.Path
if len(path) == 0 {
route := mux.CurrentRoute(r)
path, _ = route.GetPathTemplate()
}
2024-11-17 03:56:47 +01:00
timer := prometheus.NewTimer(HttpDuration.WithLabelValues(pr.Name, path))
2024-11-10 17:06:58 +01:00
2024-11-17 03:56:47 +01:00
ResponseStatus.WithLabelValues(strconv.Itoa(http.StatusOK)).Inc()
TotalRequests.WithLabelValues(pr.Name, path).Inc()
2024-11-10 17:06:58 +01:00
timer.ObserveDuration()
next.ServeHTTP(w, r)
})
}