Skip to content

Modern Docker Management, Designed for Everyone

chore: cleanup slog router logger context

Kyle Mendelle4f73e4a3f92
diff --git a/backend/internal/bootstrap/logger_bootstrap.go b/backend/internal/bootstrap/logger_bootstrap.go
index 97df18a3c..2725623f3 100644
--- a/backend/internal/bootstrap/logger_bootstrap.go
+++ b/backend/internal/bootstrap/logger_bootstrap.go
@@ -2,6 +2,7 @@ package bootstrap
import (
"context"
+ "fmt"
"log/slog"
"os"
"strings"
@@ -15,10 +16,7 @@ import (
"gorm.io/gorm/logger"
)
-// timeFilterHandler wraps a slog.Handler and removes redundant time attributes
-// from grouped attributes (like request.time and response.time emitted by HTTP
-// request loggers such as slog-echo).
-type timeFilterHandler struct {
+type requestLogHandler struct {
handler slog.Handler
}
@@ -27,66 +25,102 @@ type attrFilterHandler struct {
dropKeys map[string]struct{}
}
-func (h *timeFilterHandler) Enabled(ctx context.Context, level slog.Level) bool {
+func (h *requestLogHandler) Enabled(ctx context.Context, level slog.Level) bool {
return h.handler.Enabled(ctx, level)
}
-func (h *timeFilterHandler) Handle(ctx context.Context, r slog.Record) error {
- // Filter out time attributes from groups
- var filteredAttrs []slog.Attr
+func (h *requestLogHandler) Handle(ctx context.Context, r slog.Record) error {
+ var attrs []slog.Attr
+ var requestAttrs, responseAttrs []slog.Attr
+ var hasRequest, hasResponse bool
+
r.Attrs(func(a slog.Attr) bool {
- if a.Value.Kind() == slog.KindGroup {
- filtered := filterGroupTimeAttrs(a)
- filteredAttrs = append(filteredAttrs, filtered)
- } else {
- filteredAttrs = append(filteredAttrs, a)
+ a.Value = a.Value.Resolve()
+ switch {
+ case a.Key == "request" && a.Value.Kind() == slog.KindGroup:
+ requestAttrs = a.Value.Group()
+ hasRequest = true
+ case a.Key == "response" && a.Value.Kind() == slog.KindGroup:
+ responseAttrs = a.Value.Group()
+ hasResponse = true
+ default:
+ attrs = append(attrs, a)
}
return true
})
- // Create a new record without the original attrs
- newRecord := slog.NewRecord(r.Time, r.Level, r.Message, r.PC)
- newRecord.AddAttrs(filteredAttrs...)
-
- return h.handler.Handle(ctx, newRecord)
-}
-
-func filterGroupTimeAttrs(a slog.Attr) slog.Attr {
- if a.Value.Kind() != slog.KindGroup {
- return a
+ if !hasRequest || !hasResponse {
+ return h.handler.Handle(ctx, r)
}
- var filtered []slog.Attr
- for _, attr := range a.Value.Group() {
- // Skip "time" attributes within groups (request.time, response.time)
- if attr.Key == "time" {
- continue
+ condensedAttrs := make([]slog.Attr, 0, 10+len(attrs))
+ debugAttrs := make([]slog.Attr, 0, 6)
+ debug := h.handler.Enabled(ctx, slog.LevelDebug)
+
+ for _, a := range requestAttrs {
+ a.Value = a.Value.Resolve()
+ switch a.Key {
+ case "method", "path":
+ condensedAttrs = append(condensedAttrs, a)
+ case "host", "route":
+ if debug {
+ debugAttrs = append(debugAttrs, a)
+ }
+ case "length":
+ if debug {
+ a.Key = "request_length"
+ debugAttrs = append(debugAttrs, a)
+ }
+ case "query", "referer":
+ if debug && a.Value.Kind() == slog.KindString && a.Value.String() != "" {
+ debugAttrs = append(debugAttrs, a)
+ }
}
- // Recursively filter nested groups
- if attr.Value.Kind() == slog.KindGroup {
- filtered = append(filtered, filterGroupTimeAttrs(attr))
- } else {
- filtered = append(filtered, attr)
+ }
+
+ for _, a := range responseAttrs {
+ a.Value = a.Value.Resolve()
+ switch a.Key {
+ case "status":
+ condensedAttrs = append(condensedAttrs, a)
+ case "latency":
+ a.Key = "duration"
+ condensedAttrs = append(condensedAttrs, a)
+ case "length":
+ if debug {
+ a.Key = "response_length"
+ debugAttrs = append(debugAttrs, a)
+ }
}
}
- return slog.Group(a.Key, anySlice(filtered)...)
+ condensedAttrs = append(condensedAttrs, debugAttrs...)
+ for _, a := range attrs {
+ condensedAttrs = append(condensedAttrs, normalizeRequestLogErrorInternal(a))
+ }
+
+ newRecord := slog.NewRecord(r.Time, r.Level, r.Message, r.PC)
+ newRecord.AddAttrs(condensedAttrs...)
+
+ return h.handler.Handle(ctx, newRecord)
}
-func anySlice(attrs []slog.Attr) []any {
- result := make([]any, len(attrs))
- for i, a := range attrs {
- result[i] = a
+func normalizeRequestLogErrorInternal(a slog.Attr) slog.Attr {
+ if a.Key != "error" {
+ return a
+ }
+ if value, ok := a.Value.Any().(map[string]any); ok {
+ return slog.String("error", fmt.Sprint(value["message"]))
}
- return result
+ return a
}
-func (h *timeFilterHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
- return &timeFilterHandler{handler: h.handler.WithAttrs(attrs)}
+func (h *requestLogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
+ return &requestLogHandler{handler: h.handler.WithAttrs(attrs)}
}
-func (h *timeFilterHandler) WithGroup(name string) slog.Handler {
- return &timeFilterHandler{handler: h.handler.WithGroup(name)}
+func (h *requestLogHandler) WithGroup(name string) slog.Handler {
+ return &requestLogHandler{handler: h.handler.WithGroup(name)}
}
func (h *attrFilterHandler) Enabled(ctx context.Context, level slog.Level) bool {
@@ -143,8 +177,7 @@ func SetupSlogLogger(cfg *config.Config) {
})
}
- // Wrap with timeFilterHandler to remove redundant time attributes from slog-echo
- h = &timeFilterHandler{handler: h}
+ h = &requestLogHandler{handler: h}
slog.SetDefault(slog.New(h))
}
diff --git a/backend/internal/bootstrap/logger_bootstrap_test.go b/backend/internal/bootstrap/logger_bootstrap_test.go
new file mode 100644
index 000000000..ceb102bdb
--- /dev/null
+++ b/backend/internal/bootstrap/logger_bootstrap_test.go
@@ -0,0 +1,64 @@
+package bootstrap
+
+import (
+ "bytes"
+ "log/slog"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestRequestLogHandler(t *testing.T) {
+ t.Run("condenses slog-echo records", func(t *testing.T) {
+ var buf bytes.Buffer
+ logger := slog.New(&requestLogHandler{
+ handler: slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelInfo}),
+ })
+
+ logger.LogAttrs(t.Context(), slog.LevelWarn, "Not Found",
+ slog.Group("request",
+ slog.Time("time", time.Now()),
+ slog.String("method", "GET"),
+ slog.String("host", "localhost:3552"),
+ slog.String("path", "/api/missing"),
+ slog.String("query", ""),
+ slog.Any("params", map[string]string{"id": "123"}),
+ slog.String("route", ""),
+ slog.String("referer", "https://example.com"),
+ slog.Int("length", 0),
+ ),
+ slog.Group("response",
+ slog.Time("time", time.Now()),
+ slog.Duration("latency", 1500*time.Microsecond),
+ slog.Int("status", 404),
+ slog.Int("length", 24),
+ ),
+ slog.Any("error", map[string]any{
+ "code": 404,
+ "message": "Not Found",
+ "internal": nil,
+ }),
+ )
+
+ output := buf.String()
+ assert.Contains(t, output, "method=GET")
+ assert.Contains(t, output, "status=404")
+ assert.Contains(t, output, "duration=")
+ assert.Contains(t, output, `error="Not Found"`)
+ assert.NotContains(t, output, "request.params")
+ assert.NotContains(t, output, "request.referer")
+ assert.NotContains(t, output, "map[code:")
+ })
+
+ t.Run("passes plain records through unchanged", func(t *testing.T) {
+ var buf bytes.Buffer
+ logger := slog.New(&requestLogHandler{
+ handler: slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelInfo}),
+ })
+
+ logger.InfoContext(t.Context(), "plain record", "component", "scheduler")
+
+ assert.Contains(t, buf.String(), "msg=\"plain record\" component=scheduler")
+ })
+}
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index e1492af74..b9d511fee 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -73,7 +73,10 @@ func shouldLogRequestInternal(c echo.Context) bool {
// edge tunnel requests plus high-volume endpoints (health, WS, static).
func requestLoggerMiddlewareInternal() echo.MiddlewareFunc {
loggerMiddleware := slogecho.NewWithConfig(slog.Default(), slogecho.Config{
- Filters: []slogecho.Filter{shouldLogRequestInternal},
+ DefaultLevel: slog.LevelInfo,
+ ClientErrorLevel: slog.LevelWarn,
+ ServerErrorLevel: slog.LevelError,
+ Filters: []slogecho.Filter{shouldLogRequestInternal},
})
return func(next echo.HandlerFunc) echo.HandlerFunc {
diff --git a/go.work.sum b/go.work.sum
index 648f93eb7..a8d44ead2 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -2076,6 +2076,8 @@ go.etcd.io/gofail v0.2.0 h1:p19drv16FKK345a09a1iubchlw/vmRuksmRzgBIGjcA=
go.etcd.io/gofail v0.2.0/go.mod h1:nL3ILMGfkXTekKI3clMBNazKnjUZjYLKmBHzsVAnC1o=
go.etcd.io/raft/v3 v3.6.0 h1:5NtvbDVYpnfZWcIHgGRk9DyzkBIXOi8j+DDp1IcnUWQ=
go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo=
+go.getarcane.app/sys/cgroup v0.1.1 h1:c39W8FDqMXlKOZrpH+itaY+t8oC0tva0+6ztTrKvVIg=
+go.getarcane.app/sys/cgroup v0.1.1/go.mod h1:2dUDhWV8qe9LRnLIqa5VQDhdWbTQ04EepttdIAe9dcM=
go.getarcane.app/updater v0.3.6 h1:+BqoycaRsHj+cLVSzcYQuqbHxUKbtmaozMNblz5bVSw=
go.getarcane.app/updater v0.3.6/go.mod h1:2ENitZR/lA5MuBn60OZYR5wvU3ZCE+pAgfrebfOlRDA=
go.getarcane.app/updater v0.3.7 h1:WqHsxudvt8gvCR7iSHdxdzwH0+hM0FAh64bSypBX9Mo=