error-pages/internal/http/common/middlewares.go

69 lines
1.7 KiB
Go
Raw Normal View History

2021-09-29 15:38:50 +00:00
package common
import (
"strings"
"time"
"github.com/valyala/fasthttp"
"go.uber.org/zap"
)
func LogRequest(h fasthttp.RequestHandler, log *zap.Logger) fasthttp.RequestHandler {
2022-02-23 06:09:54 +00:00
const headersSeparator = ": "
2021-09-29 15:38:50 +00:00
2022-02-23 06:09:54 +00:00
return func(ctx *fasthttp.RequestCtx) {
var ua = string(ctx.UserAgent())
2021-09-29 15:38:50 +00:00
if strings.Contains(strings.ToLower(ua), "healthcheck") { // skip healthcheck requests logging
2022-02-23 06:09:54 +00:00
h(ctx)
2021-09-29 15:38:50 +00:00
return
}
2022-02-23 06:09:54 +00:00
var reqHeaders = make([]string, 0, 24) //nolint:gomnd
ctx.Request.Header.VisitAll(func(key, value []byte) {
reqHeaders = append(reqHeaders, string(key)+headersSeparator+string(value))
})
var startedAt = time.Now()
h(ctx)
var respHeaders = make([]string, 0, 16) //nolint:gomnd
ctx.Response.Header.VisitAll(func(key, value []byte) {
respHeaders = append(respHeaders, string(key)+headersSeparator+string(value))
})
2021-09-29 15:38:50 +00:00
log.Info("HTTP request processed",
zap.String("useragent", ua),
zap.String("method", string(ctx.Method())),
zap.String("url", string(ctx.RequestURI())),
2021-10-06 17:38:00 +00:00
zap.String("referer", string(ctx.Referer())),
2021-09-29 15:38:50 +00:00
zap.Int("status_code", ctx.Response.StatusCode()),
2022-01-27 14:28:11 +00:00
zap.String("content_type", string(ctx.Response.Header.ContentType())),
2021-09-29 15:38:50 +00:00
zap.Bool("connection_close", ctx.Response.ConnectionClose()),
zap.Duration("duration", time.Since(startedAt)),
2022-02-23 06:09:54 +00:00
zap.Strings("request_headers", reqHeaders),
zap.Strings("response_headers", respHeaders),
2021-09-29 15:38:50 +00:00
)
}
}
2022-01-28 15:42:08 +00:00
type metrics interface {
IncrementTotalRequests()
ObserveRequestDuration(t time.Duration)
}
func DurationMetrics(h fasthttp.RequestHandler, m metrics) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
var startedAt = time.Now()
h(ctx)
m.IncrementTotalRequests()
m.ObserveRequestDuration(time.Since(startedAt))
}
}