Files
summercms/modules/surf/accesslog.go
Jakub Zych 2d68eab3c0 feat(14.2-01): opt-in http.access_log request log in surf
- one Info record "http request" per request with method, matched route
  pattern, status and duration_ms; path without the query only when no
  route matched
- the matched route records its pattern through a request-scoped entry,
  so locale prefix rewrites do not hide it
- logs through the published *slog.Logger or slog.Default; off by default
- surf README, logging and configuration docs describe the key
2026-10-11 17:42:51 +02:00

115 lines
3.6 KiB
Go

package surf
import (
"context"
"log/slog"
"net/http"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
)
// accessLogKey is the config key that turns the request log on.
const accessLogKey = "http.access_log"
// accessLogMessage is the message of every request log record.
const accessLogMessage = "http request"
// accessEntry is the request-scoped slot the matched route writes its
// pattern into. A pointer travels in the context, so the pattern reaches
// the access log even when stripLocalePrefix hands ServeMux a copied
// request whose Pattern the outer middleware never sees.
type accessEntry struct {
pattern string
}
type accessEntryKey struct{}
// accessLogEnabled reports whether http.access_log is true.
func accessLogEnabled(app *backpack.App) bool {
return app != nil && app.Config != nil && app.Config.Bool(accessLogKey)
}
// accessLog logs one Info record "http request" per request after it is
// served, with method, pattern (the matched route, "" when none matched),
// status and duration_ms (whole milliseconds). Only when no route matched
// (a ServeMux 404 or 405, or a CORS preflight answered before routing) is
// path added, set to the URL path without the query string. The query
// string, headers, the remote address and a matched route's raw path are
// never logged: share and invitation tokens travel in paths. The logger is
// the app's published *slog.Logger, else slog.Default (which the generated
// main wraps in the redacting sunscreen handler).
func accessLog(app *backpack.App, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
entry := &accessEntry{}
rec := &statusRecorder{ResponseWriter: w}
next.ServeHTTP(rec, req.WithContext(context.WithValue(req.Context(), accessEntryKey{}, entry)))
status := rec.status
if status == 0 {
status = http.StatusOK
}
attrs := []slog.Attr{
slog.String("method", req.Method),
slog.String("pattern", entry.pattern),
slog.Int("status", status),
slog.Int64("duration_ms", time.Since(start).Milliseconds()),
}
if entry.pattern == "" {
attrs = append(attrs, slog.String("path", req.URL.Path))
}
accessLogger(app).LogAttrs(req.Context(), slog.LevelInfo, accessLogMessage, attrs...)
})
}
// accessLogger is the app's published logger, else slog.Default.
func accessLogger(app *backpack.App) *slog.Logger {
if app != nil {
if log, ok := app.Lookup[*slog.Logger](); ok && log != nil {
return log
}
}
return slog.Default()
}
// recordPattern stores pattern in the request's access log entry, when the
// access log put one into the context, before serving the route.
func recordPattern(pattern string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if entry, ok := req.Context().Value(accessEntryKey{}).(*accessEntry); ok && entry != nil {
entry.pattern = pattern
}
next.ServeHTTP(w, req)
})
}
// statusRecorder remembers the first status written; a Write without a
// WriteHeader is a 200. Flush and Unwrap keep http.ResponseController
// working through it.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (w *statusRecorder) WriteHeader(status int) {
if w.status == 0 {
w.status = status
}
w.ResponseWriter.WriteHeader(status)
}
func (w *statusRecorder) Write(p []byte) (int, error) {
if w.status == 0 {
w.status = http.StatusOK
}
return w.ResponseWriter.Write(p)
}
func (w *statusRecorder) Flush() {
if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
func (w *statusRecorder) Unwrap() http.ResponseWriter { return w.ResponseWriter }