atMostEvery

public abstract API atMostEvery(int n, TimeUnit unit)

Modifies the current log statement to be emitted at most once per specified time period. The specified duration must not be negative, and it is expected, but not required, that it is constant. In the absence of any other rate limiting, this method always allows the first invocation of any log statement to be emitted.

Note that for performance reasons atMostEvery() is explicitly not intended to perform "proper" rate limiting to produce a limited average rate over many samples.

Behaviour

A call to atMostEvery() will emit the current log statement if:

  currentTimestampNanos >= lastTimestampNanos + unit.toNanos(n)
where currentTimestampNanos is the timestamp of the current log statement and lastTimestampNanos is a time stamp of the last log statement that was emitted.

The effect of this is that when logging invocation is relatively infrequent, the period between emitted log statements can be higher than the specified duration. For example if the following log statement were called every 600ms:


  logger.atFine().atMostEvery(2, SECONDS).log(...);
logging would occur after 0s, 2.4s and 4.8s (not 4.2s), giving an effective duration of 2.4s between log statements over time.

Providing a zero length duration (ie, n == 0) disables rate limiting and makes this method an effective no-op.

Granularity

Because the implementation of this feature relies on a nanosecond timestamp provided by the backend, the actual granularity of the underlying clock used may vary, and it is possible to specify a time period smaller than the smallest visible time increment. If this occurs, then the effective rate limit applied to the log statement will be the smallest available time increment. For example, if the system clock granularity is 1 millisecond, and a log statement is called with atMostEvery(700, MICROSECONDS), the effective rate of logging (even averaged over long periods) could never be more than once every millisecond.

Notes

If multiple rate limiters are used for a single log statement, that log statement will only be emitted once all rate limiters have reached their threshold, and when a log statement is emitted all the rate limiters are reset. So even if the rate limit duration has expired, it does not mean that logging will occur.

When rate limiting is active, a "skipped" count is added to log statements to indicate how many logs were disallowed since the last log statement was emitted.

If this method is called multiple times for a single log statement, the last invocation will take precedence.

Parameters

n

the minimum number of time units between emitted log statements

unit

the time unit for the duration

Throws

if n is negative.