Signature-Aware Log Sampler

Keep the first occurrence of each log signature and sample the repeats, cutting volume while preserving new messages.

JavascriptResilience

Code

javascriptsnippet
22 lines
export class LogSampler {
  constructor({ rate = 0.01, alwaysKeep = () => false } = {}) {
    this.rate = rate;
    this.alwaysKeep = alwaysKeep;
    this.seen = new Set();
  }

  shouldEmit(signature) {
    if (this.alwaysKeep(signature)) return true;
    if (!this.seen.has(signature)) {
      this.seen.add(signature);
      return true;
    }
    return Math.random() < this.rate;
  }

  emit(signature, write) {
    if (!this.shouldEmit(signature)) return false;
    write({ signature, sampledRate: this.rate });
    return true;
  }
}

Inside the snippet

The working surface is the class LogSampler — everything else is wiring.

Putting it to use

The surface worth importing is LogSampler; the helpers around it are private to the snippet.

Core lines

constructor({ rate = 0.01, alwaysKeep = () => false } = {}) {
this.rate = rate;
this.alwaysKeep = alwaysKeep;
this.seen = new Set();
}
if (!this.shouldEmit(signature)) return false;
if (this.alwaysKeep(signature)) return true;

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library.