RingBufferSink

class RingBufferSink(val capacity: Int, val maxLevel: TraceLevel = TraceLevel.Pool) : TraceSink(source)

Keeps the last capacity events, for tests, crash reports and ad-hoc export.

Lock-free and safe for concurrent emit from many threads. Implementation: a sequence counter claims a slot (seq % capacity) among capacity AtomicReferences (the common stdlib has no atomic array primitive); the slot holds an immutable (seq, event) pair and is replaced by compare-and-set only when the stored sequence is older, so a delayed writer can never overwrite a newer event. snapshot reads the slots and orders by sequence. This avoids copying the whole buffer on every emit (which a CAS loop over one immutable snapshot would do). An event whose slot is claimed but not yet written may be briefly absent from a concurrent snapshot, which is acceptable for a diagnostic sink.

Example:

val ring = RingBufferSink(capacity = 256)
// ... run traced work ...
ring.snapshot().forEach(::println)

Once more than capacity events were emitted, the oldest ones are overwritten.

Requires opting in to ExperimentalStructuredCoroutines.

Parameters

capacity

maximum number of retained events; must be positive.

maxLevel

highest TraceLevel this sink accepts.

See also

Throws

if capacity is not positive.

Constructors

Link copied to clipboard
constructor(capacity: Int, maxLevel: TraceLevel = TraceLevel.Pool)

Properties

Link copied to clipboard
Link copied to clipboard

Functions

Link copied to clipboard
fun clear()

Drops every retained event. Events emitted concurrently with the call may survive it.

Link copied to clipboard
open override fun emit(event: TraceEvent)

Receives one event. See the contract in the type documentation.

Link copied to clipboard
open override fun isEnabled(level: TraceLevel): Boolean

Whether this sink wants events of level. Defaults to true for every level.

Link copied to clipboard

Returns a copy of the retained events, oldest first (at most capacity elements). The list is not updated by later events.