package logging import ( "bytes" "log/slog" "testing" ) func TestRingHandler_KeepsErrorsNewestFirst(t *testing.T) { ring := NewErrorRing(3) var out bytes.Buffer log := slog.New(newRingHandler(slog.NewTextHandler(&out, nil), ring)).With("component", "scan") log.Info("fine") log.Warn("odd") for _, msg := range []string{"one", "two", "three", "four"} { log.WithGroup("job").Error(msg, "n", len(msg)) } got, total := ring.Snapshot() if total != 4 { t.Errorf("total = %d, want 4 (info and warn are not errors)", total) } if len(got) != 3 { t.Fatalf("kept %d, want 3", len(got)) } for i, want := range []string{"four", "three", "two"} { if got[i].Message != want { t.Errorf("kept[%d] = %q, want %q", i, got[i].Message, want) } } if got[0].Attrs != "component=scan job.n=4" { t.Errorf("attrs = %q", got[0].Attrs) } // Every record still reaches the log stream. if n := bytes.Count(out.Bytes(), []byte("\n")); n != 6 { t.Errorf("log lines = %d, want 6", n) } } func TestErrorRing_BeforeItFills(t *testing.T) { ring := NewErrorRing(5) ring.add(LoggedError{Message: "a"}) ring.add(LoggedError{Message: "b"}) got, total := ring.Snapshot() if total != 2 || len(got) != 2 || got[0].Message != "b" || got[1].Message != "a" { t.Errorf("got %+v total %d, want b, a", got, total) } }