How to Implement Log Sampling and Redaction
Control log volume and protect secrets: sample the high-volume events, always keep errors, and redact secrets before they are written.
On this page
Introduction
Logs at scale have two problems: volume and secrets. A per-request debug line, logged for every request, produces an enormous volume that costs money to store and is hard to search, while adding little per line. A secret passed into a log call leaks into the log store, which is often more broadly accessible than the secret store. Log sampling controls the volume; log redaction controls the secrets.
This tutorial covers sampling the high-volume events, keeping the errors and slow requests in full, redacting secrets before they are written, and testing both. The examples use a structured logger, and the controls apply wherever logs are written.
Sample the repetitive high-volume events
Sample the events that are both frequent and low-information, such as a per-request debug line or a routine info line. Log a fraction, driven by a sample rate, so the volume drops while a representative sample remains. Record the rate, so a count derived from the sample can be scaled back to an estimate of the true count, which keeps the sample useful for trends.
Sampling should be deterministic per request where possible, so a request is sampled entirely or not at all, and its lines are not split. Hash the request id to decide, so the same id always makes the same decision. This keeps a sampled request’s logs coherent, rather than a random subset of its lines, which would be confusing to read.
import { createHash } from 'node:crypto';
function shouldSample(requestId, rate) {
const h = createHash('sha256').update(requestId).digest();
const n = h.readUInt32BE(0) / 0xffffffff; // deterministic per request id
return n < rate;
}
if (shouldSample(req.id, 0.1)) {
req.log.debug({ route: req.route }, 'request_detail'); // 10% of requests
}
Never sample the errors or the slow requests
Exempt the logs you always need: the errors, the slow requests, the rare events, and the security-relevant lines. These are low-volume and high-information, so sampling them loses the exact lines you need in an incident. The sampling applies to the repetitive high-volume lines, and everything else is logged in full.
The distinction is volume versus information. A line logged a million times with little per-line value is a sampling candidate; a line logged a few times that explains a failure is not. Keep the errors in full, and sample the routine traffic, so the log store holds the interesting events and a sample of the routine ones.
// route by level and outcome: errors and slow always, routine sampled
function emit(req, level, fields, msg) {
const isError = level === 'error';
const isSlow = fields.durationMs > 500;
if (isError || isSlow || shouldSample(req.id, 0.1)) {
req.log[level](fields, msg);
}
}
Redact secrets before the line is written
The logger should drop the secret-bearing fields and headers before writing, so a secret passed into a log call never reaches the store. Configure the redaction by field path for the structured fields, such as a password, a token, and an authorization header, and by pattern for the free-text message. Redacting at the logger centralizes the rule, so a call site does not have to remember.
Redact both known field names and value patterns. A field named password is redacted by name; a token embedded in a free-text message is redacted by pattern. The name-based redaction catches the structured case, and the pattern-based catches the secret that slipped into a string. Test both, because a secret can enter either path.
const logger = pino({
redact: {
paths: ['password', 'token', 'req.headers.authorization', 'req.headers.cookie'],
remove: true,
},
});
logger.info({ password: 'hunter2', user: 'a' }, 'login');
// {"level":30,...,"user":"a","msg":"login"} — password is gone
Redact by pattern for free text
A secret can appear in a message that is not a structured field, such as an error string that echoes a URL with an embedded token. A pattern-based scrubber replaces the known secret shapes in the text before it is written: a bearer token, a long base64 string in a query, a credit-card-shaped number. This catches the secret that a name-based redaction would miss.
Keep the patterns specific, so a redaction does not remove legitimate data. A pattern for a bearer token matches the Bearer prefix and the token after it; a pattern for a card number matches the digit grouping. Over-broad patterns redact real content, which makes the logs less useful, so a specific pattern is better than a wide one.
function scrub(text) {
return text
.replace(/Bearer\s+[A-Za-z0-9._-]+/g, 'Bearer <REDACTED>')
.replace(/\b\d{13,19}\b/g, '<CARD>')
.replace(/api_key=[A-Za-z0-9]+/g, 'api_key=<REDACTED>');
}
// apply to a free-text message before it is logged
Test the sampling and the redaction
Test the sampling by driving many events with a known rate and asserting the logged count is close to the rate times the total, and that the same request id always makes the same sampling decision. Test the redaction by logging a secret field and a message with a secret pattern and asserting neither appears in the output. Test that an error is never sampled, by driving errors and asserting all are logged.
# drive 1000 sampled events at 10%: the logged count should be near 100
# and a log call with a password field must not contain the password value
node -e '
const out = [];
const logger = makeLogger({ sink: (line) => out.push(line), sampleRate: 0.1 });
for (let i = 0; i < 1000; i++) logger.info({ requestId: String(i), password: "x" }, "evt");
const secrets = out.filter((l) => l.includes(""password"")).length;
console.log("logged:", out.length, "secret leaks:", secrets); // near 100, 0
'
Common pitfalls
Sampling the errors so the incident’s lines are missing, sampling per line so a request’s logs are split, a non-deterministic sample so the count cannot be scaled, redacting only by name so a secret in free text leaks, and an over-broad pattern that removes legitimate content are the recurring mistakes. Sampling the high-volume lines with a recorded rate, a deterministic per-request decision, exempting errors and slow requests, name and pattern redaction, and specific patterns address them.
Conclusion
Log sampling controls the volume and redaction controls the secrets. Sample the repetitive high-volume events with a recorded rate and a deterministic per-request decision, never sample the errors or slow requests, redact the secret fields and patterns before writing, and test both. Self-check by asserting the sampled count matches the rate and that a secret field never appears in the output. Then the logs are affordable and safe.
Sources: OpenTelemetry: Sampling, OWASP: Logging cheat sheet, MDN: JSON and structured data.
FAQ
- Why sample logs?
- High-volume events, such as a per-request debug line, can dominate the log volume and the cost while adding little. Sampling keeps a representative fraction so you can still see the behavior, at a lower volume and cost. Errors and slow requests are exempt, because those are the ones you need in full.
- Why redact at the logger?
- Redacting at the logger centralizes the rule, so a secret passed into a log call is dropped without each call site remembering. A secret that reaches the log store is a leak, and the log store is often broader-access than the secret store, so the redaction is a security control, not a tidy-up.
Report a problem with this articleOpens a pre-filled issue on GitHub.