diff --git a/internal/logging/attrs_test.go b/internal/logging/attrs_test.go index 4c00db325..0d8a9a44c 100644 --- a/internal/logging/attrs_test.go +++ b/internal/logging/attrs_test.go @@ -1,6 +1,9 @@ package logging import ( + "encoding/json" + "errors" + "fmt" "log/slog" "testing" "time" @@ -74,6 +77,74 @@ func TestFlattenAttrs(t *testing.T) { } } +// TestFlattenAttrsConvertsErrorsToTheirMessageString pins the regression that +// shipped archie-core's task/system logs full of "err":{}: SystemLogHandler +// and FeedHandler both json.Marshal Entry.Fields directly rather than going +// through slog's own JSON handler, and encoding/json has no idea an `error` +// value should become its message -- it reflects the concrete type's fields, +// which for a stdlib error are unexported, so the message vanishes into `{}`. +func TestFlattenAttrsConvertsErrorsToTheirMessageString(t *testing.T) { + tests := []struct { + name string + err error + want string + }{ + {name: "plain error", err: errors.New("boom"), want: "boom"}, + {name: "wrapped error", err: fmt.Errorf("outer: %w", errors.New("inner")), want: "outer: inner"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + record := slog.NewRecord(time.Now(), slog.LevelError, "handle failed", 0) + record.AddAttrs(slog.Any("err", tt.err)) + + got := FlattenAttrs(record, nil, nil) + + value, ok := got["err"].(string) + if !ok { + t.Fatalf("FlattenAttrs()[%q] = %#v (%T), want a string", "err", got["err"], got["err"]) + } + if value != tt.want { + t.Errorf("FlattenAttrs()[%q] = %q, want %q", "err", value, tt.want) + } + + encoded, marshalErr := json.Marshal(map[string]any{"err": got["err"]}) + if marshalErr != nil { + t.Fatalf("json.Marshal: %v", marshalErr) + } + if string(encoded) == `{"err":{}}` { + t.Errorf("json.Marshal(%#v) = %s, error message was discarded", got["err"], encoded) + } + }) + } +} + +// typedNilError has a pointer receiver Error() that dereferences itself, so +// calling it on a nil *typedNilError panics -- the classic Go footgun where +// a non-nil error interface wraps a nil concrete pointer. +type typedNilError struct{ msg string } + +func (e *typedNilError) Error() string { return e.msg } + +// TestFlattenAttrsDoesNotPanicOnATypedNilError pins the case +// TestFlattenAttrsConvertsErrorsToTheirMessageString's err != nil check +// misses: `var e *typedNilError; var err error = e` is a non-nil interface, +// so a naive nil check would call Error() on a nil receiver and crash the +// process -- the one failure mode a logging package must never have. +func TestFlattenAttrsDoesNotPanicOnATypedNilError(t *testing.T) { + var e *typedNilError + var err error = e + + record := slog.NewRecord(time.Now(), slog.LevelError, "handle failed", 0) + record.AddAttrs(slog.Any("err", err)) + + got := FlattenAttrs(record, nil, nil) // must not panic + + if _, err := json.Marshal(map[string]any{"err": got["err"]}); err != nil { + t.Fatalf("json.Marshal: %v", err) + } +} + func newTestRecord(kvs ...string) slog.Record { r := slog.NewRecord(time.Now(), slog.LevelInfo, "msg", 0) for i := 0; i+1 < len(kvs); i += 2 { diff --git a/internal/logging/feed.go b/internal/logging/feed.go index 7f2b655fb..3d0636d12 100644 --- a/internal/logging/feed.go +++ b/internal/logging/feed.go @@ -3,6 +3,7 @@ package logging import ( "context" "log/slog" + "reflect" "sync" "sync/atomic" ) @@ -170,5 +171,37 @@ func addAttr(fields map[string]any, groups []string, attr slog.Attr) { key = group + "." + key } } - fields[key] = attr.Value.Any() + fields[key] = attrValue(attr.Value) +} + +// attrValue resolves a slog attr to what Entry.Fields should hold on the +// wire. Both consumers of FlattenAttrs (SystemLogHandler, FeedHandler) +// json.Marshal Entry.Fields directly rather than through slog's own JSON +// handler, so an `error` value must be resolved to its message string here: +// encoding/json has no Error()-aware special case, and the concrete types +// behind almost every Go error (errors.errorString, fmt.wrapError, ...) hold +// only unexported fields, which marshal to `{}` and silently discard the +// message. +func attrValue(v slog.Value) any { + if v.Kind() == slog.KindAny { + if err, ok := v.Any().(error); ok && !isNilError(err) { + return err.Error() + } + } + return v.Any() +} + +// isNilError reports whether err is nil in the way that matters before +// calling Error(): a plain nil interface, or the classic Go footgun where a +// non-nil interface wraps a nil concrete pointer (var e *T; var err error = +// e -- err != nil is true). A logging package's whole job is to never be the +// thing that crashes the process, so this checks for both rather than +// trusting every Error() method in this module and its dependencies to +// tolerate a nil receiver. +func isNilError(err error) bool { + if err == nil { + return true + } + rv := reflect.ValueOf(err) + return rv.Kind() == reflect.Pointer && rv.IsNil() }