Files

83 lines
2.9 KiB
Go

package middleware
import (
"log/slog"
"net/http"
"slices"
"strconv"
"github.com/felixge/httpsnoop"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
"lincodex/backend/internal/adapter/primary/http/observe"
)
// otherMethod replaces a method outside the standard set in logs and
// metrics, so a client cannot write arbitrary text through it.
const otherMethod = "OTHER"
var knownMethods = []string{
http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch,
http.MethodDelete, http.MethodHead, http.MethodOptions,
}
// RequestLog logs every finished request except the paths in skip, which are
// matched exactly. A line carries the request ID, the method, the bounded
// route template (the same as in the metrics), the status and its class, the
// problem code when the response is a problem, the latency, the response
// size, and the number of query parameters.
//
// It never logs the raw path, a query key or value, a header, the client
// address, or the user agent: a path or a query can carry an address, a
// token, or another identifier that a client put there, and the access logs
// have no purpose that needs the client address. The request ID links a line
// to the handler logs of the same request.
func RequestLog(logger *slog.Logger, resolve RouteResolver, skip ...string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if slices.Contains(skip, r.URL.Path) {
next.ServeHTTP(w, r)
return
}
ctx, observed := observe.Ensure(r.Context())
captured := httpsnoop.CaptureMetrics(next, w, r.WithContext(ctx))
attributes := []slog.Attr{
slog.String("request_id", kitmiddleware.GetRequestID(ctx)),
slog.String("method", boundedMethod(r.Method)),
slog.String("route", routeTemplate(r, resolve)),
slog.Int("status", captured.Code),
slog.String("status_class", statusClass(captured.Code)),
slog.Int64("latency_ms", captured.Duration.Milliseconds()),
slog.Int64("bytes", captured.Written),
slog.Int("query_params", len(r.URL.Query())),
}
if code := observed.ProblemCode(); code != "" && captured.Code >= http.StatusBadRequest {
attributes = append(attributes, slog.String("problem_code", code))
}
level, message := slog.LevelInfo, "http request"
switch {
case captured.Code >= http.StatusInternalServerError:
level, message = slog.LevelError, "http request failed"
case captured.Code >= http.StatusBadRequest:
level, message = slog.LevelWarn, "http request error"
}
logger.LogAttrs(ctx, level, message, attributes...)
})
}
}
func boundedMethod(method string) string {
if slices.Contains(knownMethods, method) {
return method
}
return otherMethod
}
// statusClass maps a status code to 1xx-5xx, or "other" outside them.
func statusClass(status int) string {
if status < 100 || status > 599 {
return "other"
}
return strconv.Itoa(status/100) + "xx"
}