Skip to content

Commit

Permalink
fix: reset condition in burst sampler (#711) (#712)
Browse files Browse the repository at this point in the history
  • Loading branch information
crazy-pe authored Feb 26, 2025
1 parent 1869fa5 commit 0398600
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion sampler.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func (s *BurstSampler) inc() uint32 {
now := TimestampFunc().UnixNano()
resetAt := atomic.LoadInt64(&s.resetAt)
var c uint32
if now > resetAt {
if now >= resetAt {
c = 1
atomic.StoreUint32(&s.counter, c)
newResetAt := now + s.Period.Nanoseconds()
Expand Down
32 changes: 32 additions & 0 deletions sampler_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build !binary_log
// +build !binary_log

package zerolog
Expand Down Expand Up @@ -103,3 +104,34 @@ func BenchmarkSamplers(b *testing.B) {
})
}
}

func TestBurst(t *testing.T) {
sampler := &BurstSampler{Burst: 1, Period: time.Second}

t0 := time.Now()
now := t0
mockedTime := func() time.Time {
return now
}

TimestampFunc = mockedTime
defer func() { TimestampFunc = time.Now }()

scenario := []struct {
tm time.Time
want bool
}{
{t0, true},
{t0.Add(time.Second - time.Nanosecond), false},
{t0.Add(time.Second), true},
{t0.Add(time.Second + time.Nanosecond), false},
}

for i, step := range scenario {
now = step.tm
got := sampler.Sample(NoLevel)
if got != step.want {
t.Errorf("step %d (t=%s): expect %t got %t", i, step.tm, step.want, got)
}
}
}

0 comments on commit 0398600

Please sign in to comment.