authelia/internal/middlewares/metrics.go
James Elliott 001589cd6d
feat(metrics): implement prometheus metrics (#3234)
Adds ability to record metrics and gather them for Prometheus.
2022-06-14 17:20:13 +10:00

48 lines
1.1 KiB
Go

package middlewares
import (
"strconv"
"time"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/internal/metrics"
)
// NewMetricsRequest returns a middleware if provided with a metrics.Recorder, otherwise it returns nil.
func NewMetricsRequest(metrics metrics.Recorder) (middleware Basic) {
if metrics == nil {
return nil
}
return func(next fasthttp.RequestHandler) (handler fasthttp.RequestHandler) {
return func(ctx *fasthttp.RequestCtx) {
started := time.Now()
next(ctx)
statusCode := strconv.Itoa(ctx.Response.StatusCode())
requestMethod := string(ctx.Method())
metrics.RecordRequest(statusCode, requestMethod, time.Since(started))
}
}
}
// NewMetricsVerifyRequest returns a middleware if provided with a metrics.Recorder, otherwise it returns nil.
func NewMetricsVerifyRequest(metrics metrics.Recorder) (middleware Basic) {
if metrics == nil {
return nil
}
return func(next fasthttp.RequestHandler) (handler fasthttp.RequestHandler) {
return func(ctx *fasthttp.RequestCtx) {
next(ctx)
statusCode := strconv.Itoa(ctx.Response.StatusCode())
metrics.RecordVerifyRequest(statusCode)
}
}
}