rs/zerolog

Use TimestampFunc for sampling

Opened this issue · 1 comments

It is possible to set a custom timestamp function with the TimesampFunc global variable. This is very useful especially for unit tests or when using zerolog in accelerated simulations.

Unfortunately, the BurstSampler uses time.Now() and not the TimesampFunc function to sample logs. Is there a reason why you did so?

My suggestion is to use the function in the file sampler.go:

func (s *BurstSampler) inc() uint32 {
	now := TimestampFunc().UnixNano() // <- here instead of now := time.Now().UnixNano()
	resetAt := atomic.LoadInt64(&s.resetAt)
	var c uint32
	if now > resetAt {
		c = 1
		atomic.StoreUint32(&s.counter, c)
		newResetAt := now + s.Period.Nanoseconds()
		reset := atomic.CompareAndSwapInt64(&s.resetAt, resetAt, newResetAt)
		if !reset {
			// Lost the race with another goroutine trying to reset.
			c = atomic.AddUint32(&s.counter, 1)
		}
	} else {
		c = atomic.AddUint32(&s.counter, 1)
	}
	return c
}
rs commented

Feel free to submit a PR to fix this.