Skip to content

Use TimestampFunc for sampling #671

@crazy-pe

Description

@crazy-pe

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions