rs / zerolog

Zero Allocation JSON Logger
MIT License
10.33k stars 564 forks source link

Use TimestampFunc for sampling #671

Open crazy-pe opened 4 months ago

crazy-pe commented 4 months ago

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 4 months ago

Feel free to submit a PR to fix this.