Skip to content

Commit 8aa349a

Browse files
committed
log/slog: add Record.AttrsIter
1 parent 388c41c commit 8aa349a

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/log/slog/record.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package slog
66

77
import (
8+
"iter"
89
"runtime"
910
"slices"
1011
"time"
@@ -92,6 +93,13 @@ func (r Record) Attrs(f func(Attr) bool) {
9293
}
9394
}
9495

96+
// AttrsIter returns an iterator over every attribute in the [Record].
97+
func (r Record) AttrsIter() iter.Seq[Attr] {
98+
return func(yield func(Attr) bool) {
99+
r.Attrs(yield)
100+
}
101+
}
102+
95103
// AddAttrs appends the given Attrs to the [Record]'s list of Attrs.
96104
// It omits empty groups.
97105
func (r *Record) AddAttrs(attrs ...Attr) {

src/log/slog/record_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,22 @@ func TestRecordAttrs(t *testing.T) {
3636
t.Errorf("got %v, want %v", got, want)
3737
}
3838
}
39+
40+
// Early return with iterator.
41+
// Hit both loops in Record.Attrs: front and back.
42+
for _, stop := range []int{2, 6} {
43+
var got []Attr
44+
for a := range r.AttrsIter() {
45+
got = append(got, a)
46+
if len(got) < stop {
47+
break
48+
}
49+
}
50+
want := as[:stop]
51+
if !attrsEqual(got, want) {
52+
t.Errorf("got %v, want %v", got, want)
53+
}
54+
}
3955
}
4056

4157
func TestRecordSource(t *testing.T) {

0 commit comments

Comments
 (0)