feat: add prometheus metrics
All checks were successful
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 2m16s
All checks were successful
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 2m16s
This commit is contained in:
52
hello/metrics.go
Normal file
52
hello/metrics.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package hello
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
)
|
||||
|
||||
var (
|
||||
httpRequestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "http_requests_total",
|
||||
Help: "Total number of HTTP requests.",
|
||||
}, []string{"path", "method", "status"})
|
||||
|
||||
httpRequestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Name: "http_request_duration_seconds",
|
||||
Help: "Duration of HTTP requests.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}, []string{"path", "method", "status"})
|
||||
)
|
||||
|
||||
// Middleware wraps an http.HandlerFunc with Prometheus metrics
|
||||
func Middleware(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
ww := &responseWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
|
||||
next(ww, r)
|
||||
|
||||
duration := time.Since(start).Seconds()
|
||||
status := strconv.Itoa(ww.status)
|
||||
path := r.URL.Path
|
||||
method := r.Method
|
||||
|
||||
httpRequestsTotal.WithLabelValues(path, method, status).Inc()
|
||||
httpRequestDuration.WithLabelValues(path, method, status).Observe(duration)
|
||||
}
|
||||
}
|
||||
|
||||
type responseWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (rw *responseWriter) WriteHeader(code int) {
|
||||
rw.status = code
|
||||
rw.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
Reference in New Issue
Block a user