~james/core

core/spindle/middleware.go -rw-r--r-- 843 bytes
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package spindle

import (
	"log/slog"
	"net/http"
	"time"
)

func (s *Spindle) RequestLogger(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()

		next.ServeHTTP(w, r)

		// Build query params as slog.Attrs for the group
		queryParams := r.URL.Query()
		queryAttrs := make([]any, 0, len(queryParams))
		for key, values := range queryParams {
			if len(values) == 1 {
				queryAttrs = append(queryAttrs, slog.String(key, values[0]))
			} else {
				queryAttrs = append(queryAttrs, slog.Any(key, values))
			}
		}

		s.l.LogAttrs(r.Context(), slog.LevelInfo, "",
			slog.Group("request",
				slog.String("method", r.Method),
				slog.String("path", r.URL.Path),
				slog.Group("query", queryAttrs...),
				slog.Duration("duration", time.Since(start)),
			),
		)
	})
}