2021-04-10 05:58:01 +00:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/go-chi/chi/v5/middleware"
|
2021-10-28 14:35:57 +00:00
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
2021-04-10 05:58:01 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// LoggingMiddleware is used for logging info about requests to the servers configured accesslogger.
|
|
|
|
func (s *Server) LoggingMiddleware(next http.Handler) http.Handler {
|
|
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
|
|
|
t1 := time.Now()
|
|
|
|
|
|
|
|
reqID := middleware.GetReqID(r.Context())
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
/*s.AccessLogger.Debugw(r.Method,
|
|
|
|
"path", r.URL.Path,
|
|
|
|
"request-headers", r.Header,
|
|
|
|
"response-headers", ww.Header(),
|
|
|
|
)
|
|
|
|
*/
|
|
|
|
s.AccessLogger.Infow(r.Method,
|
|
|
|
"path", r.URL.Path,
|
|
|
|
"status", ww.Status(),
|
|
|
|
"written", ww.BytesWritten(),
|
|
|
|
"remote_addr", r.RemoteAddr,
|
|
|
|
"processing_time_ms", time.Since(t1).Milliseconds(),
|
|
|
|
"req_id", reqID)
|
|
|
|
}()
|
|
|
|
|
|
|
|
next.ServeHTTP(ww, r)
|
|
|
|
}
|
|
|
|
return http.HandlerFunc(fn)
|
|
|
|
}
|
2021-10-28 14:35:57 +00:00
|
|
|
|
|
|
|
type MetricsMiddleware struct {
|
|
|
|
requests *prometheus.CounterVec
|
|
|
|
latency *prometheus.HistogramVec
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mm *MetricsMiddleware) handler(next http.Handler) http.Handler {
|
|
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
|
|
|
start := time.Now()
|
|
|
|
defer func() {
|
|
|
|
mm.requests.WithLabelValues(http.StatusText(ww.Status()), r.Method, r.URL.Path).Inc()
|
|
|
|
mm.latency.WithLabelValues(http.StatusText(ww.Status()), r.Method, r.URL.Path).Observe(float64(time.Since(start).Milliseconds()))
|
|
|
|
}()
|
|
|
|
next.ServeHTTP(ww, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
return http.HandlerFunc(fn)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewMetricsMiddleware() func(next http.Handler) http.Handler {
|
|
|
|
mm := &MetricsMiddleware{}
|
|
|
|
mm.requests = prometheus.NewCounterVec(prometheus.CounterOpts{
|
|
|
|
Name: "filmblogg_http_requests_total",
|
|
|
|
Help: "Total requests processed.",
|
|
|
|
ConstLabels: prometheus.Labels{"service": "http"},
|
|
|
|
},
|
|
|
|
[]string{"code", "method", "path"},
|
|
|
|
)
|
|
|
|
|
|
|
|
mm.latency = prometheus.NewHistogramVec(
|
|
|
|
prometheus.HistogramOpts{
|
|
|
|
Name: "filmblogg_http_request_duration_milliseconds",
|
|
|
|
Help: "Request processing time.",
|
|
|
|
ConstLabels: prometheus.Labels{"service": "http"},
|
|
|
|
Buckets: []float64{100, 500, 1500},
|
|
|
|
},
|
|
|
|
[]string{"code", "method", "path"},
|
|
|
|
)
|
|
|
|
prometheus.MustRegister(mm.requests)
|
|
|
|
prometheus.MustRegister(mm.latency)
|
|
|
|
return mm.handler
|
|
|
|
}
|