close
Skip to content

Sampling Plugin Browser Server Deno Bun

NPM Version

Plugin Source

The Sampling Plugin lets you randomly drop log entries to control log volume and cost. It works with all log levels and supports rate-based, per-level, or custom callback strategies.

Installation

sh
npm install @loglayer/plugin-sampling
sh
pnpm add @loglayer/plugin-sampling
sh
yarn add @loglayer/plugin-sampling

Configuration Options

Optional Parameters

NameTypeDefaultDescription
strategy"default" | "per_level""default"Sampling strategy.
rateboolean | number1Fraction of events to keep (0-1). With "per_level" this acts as a fallback for unmapped levels.
perLevelPartial<Record<LogLevelType, boolean | number>>undefinedPer-level rates. Levels not listed fall back to rate (or 1 if rate is not set).
shouldSample(params) => booleanundefinedCallback to make a keep/drop decision. Receives the log level, messages, metadata, context, and error.

Usage

Rate-Based Sampling

Keep a percentage of all log entries:

typescript
import { LogLayer, ConsoleTransport } from "loglayer";
import { samplingPlugin } from "@loglayer/plugin-sampling";

const log = new LogLayer({
  transport: new ConsoleTransport({ logger: console }),
  plugins: [samplingPlugin({ rate: 0.1 })],  // keep ~10%
});

Per-Level Sampling

Apply different rates per level:

typescript
const log = new LogLayer({
  transport: new ConsoleTransport({ logger: console }),
  plugins: [
    samplingPlugin({
      strategy: "per_level",
      perLevel: {
        trace: 0.1,  // keep 10% of trace
        debug: 0.3,  // keep 30% of debug
        info: 0.5,   // keep 50% of info
      },
    }),
  ],
});

Custom Callback

Use a callback for content-aware filtering:

typescript
const log = new LogLayer({
  transport: new ConsoleTransport({ logger: console }),
  plugins: [
    samplingPlugin({
      shouldSample: ({ level, metadata }) => {
        // keep everything at error level or above, or logs with a userId
        return level === "error" || metadata?.userId;
      },
    }),
  ],
});

Behavior

Evaluation Order

  1. shouldSample callback (if set): Sole gate. If present, it completely replaces rate-based sampling. Returns true → kept, false → dropped. Throws → kept (fail-open).
  2. error/fatal default to 100%: Kept by default unless explicitly mapped in perLevel.
  3. per_level strategy: Checks perLevel map → unmapped → rate.
  4. default strategy: Uses rate for all non-error/fatal levels.
  • fail-open: If the shouldSample callback throws, the event is kept
  • snapshot: perLevel map is snapshotted at construction; mutating it afterward has no effect
  • rate clamping: Rates are clamped to [0, 1]. NaN/Infinity are treated as 0

Changelog

View the changelog here.