Log Redaction — Securing Sensitive Data in Logs
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Log Redaction. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Log redaction prevents sensitive data from being written to log files, protecting PII and secrets from exposure.
// Log redaction engine
class LogRedactor {
constructor() {
this.patterns = [
// Credit cards
{ pattern: /\b(?:\d[ -]*?){13,16}\b/g, replacement: '**REDACTED_CC**' },
// SSN
{ pattern: /\b\d{3}-\d{2}-\d{4}\b/g, replacement: '**REDACTED_SSN**' },
// Email
{ pattern: /\b[\w.-]+@[\w.-]+\.\w+\b/g, replacement: '**REDACTED_EMAIL**' },
// API keys
{ pattern: /(api[_-]?key|apikey|secret)[=:]["']?\w+["']?/gi, replacement: '$1=**REDACTED_KEY**' },
// JWT tokens
{ pattern: /\beyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\b/g, replacement: '**REDACTED_JWT**' },
// Phone numbers
{ pattern: /\b\+?\d{1,3}[-.\s]?\(?\d{1,4}\)?[-.\s]?\d{1,4}[-.\s]?\d{1,9}\b/g, replacement: '**REDACTED_PHONE**' }
];
this.fieldRedactions = {
'password': '**REDACTED**',
'creditCard': '**REDACTED**',
'ssn': '**REDACTED**',
'token': '**REDACTED**',
'secret': '**REDACTED**',
'authorization': '**REDACTED**',
'x-api-key': '**REDACTED**'
};
}
redactString(value) {
let redacted = value;
for (const { pattern, replacement } of this.patterns) {
redacted = redacted.replace(pattern, replacement);
}
return redacted;
}
redactObject(obj, path = '') {
if (typeof obj === 'string') return this.redactString(obj);
if (typeof obj !== 'object' || obj === null) return obj;
const redacted = Array.isArray(obj) ? [] : {};
for (const [key, value] of Object.entries(obj)) {
const keyLower = key.toLowerCase();
if (this.fieldRedactions[keyLower]) {
redacted[key] = this.fieldRedactions[keyLower];
} else {
redacted[key] = this.redactObject(value, `${path}.${key}`);
}
}
return redacted;
}
}
// Streaming redaction middleware
function redactionMiddleware(req, res, next) {
const originalJson = res.json.bind(res);
res.json = (body) => {
if (res.statusCode >= 400) {
body = redactor.redactObject(body);
}
return originalJson(body);
};
next();
}
Log redaction ensures Compliance with data protection regulations and prevents accidental credential exposure.
← Previous
Centralized Logging Architecture — Designing Log Infrastructure for Scale
Next →
Structured Error Logging — Logging Errors with Rich Context
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro