Skip to content

Backend Secure Logging — Logging Without Exposing Sensitive Data

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Backend Secure Logging. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Secure logging prevents sensitive data leakage through application logs while maintaining debugging capabilities.

// PII/secret redaction pipeline
class SecureLogger {
  constructor() {
    this.redactionPatterns = [
      { pattern: /"password"\s*:\s*"[^"]+"/g, replacement: '"password":"[REDACTED]"' },
      { pattern: /"token"\s*:\s*"[^"]+"/g, replacement: '"token":"[REDACTED]"' },
      { pattern: /"secret"\s*:\s*"[^"]+"/g, replacement: '"secret":"[REDACTED]"' },
      { pattern: /"creditCard"\s*:\s*"[^"]+"/g, replacement: '"creditCard":"[REDACTED]"' },
      { pattern: /"ssn"\s*:\s*"[^"]+"/g, replacement: '"ssn":"[REDACTED]"' },
      { pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, replacement: '[EMAIL REDACTED]' },
      { pattern: /\b\d{3}-\d{2}-\d{4}\b/g, replacement: '[SSN REDACTED]' },
      { pattern: /(api[_-]?key|apikey)[=:]["']?\w+["']?/gi, replacement: '$1=[REDACTED]' }
    ];
  }

  sanitize(data) {
    if (typeof data === 'string') {
      return this.redactString(data);
    }
    if (typeof data === 'object' && data !== null) {
      return this.redactObject(data);
    }
    return data;
  }

  redactString(str) {
    let sanitized = str;
    for (const { pattern, replacement } of this.redactionPatterns) {
      sanitized = sanitized.replace(pattern, replacement);
    }
    return sanitized;
  }

  redactObject(obj) {
    const sanitized = Array.isArray(obj) ? [] : {};
    for (const [key, value] of Object.entries(obj)) {
      const lowerKey = key.toLowerCase();
      if (['password', 'secret', 'token', 'authorization', 'cookie'].includes(lowerKey)) {
        sanitized[key] = '[REDACTED]';
      } else {
        sanitized[key] = this.sanitize(value);
      }
    }
    return sanitized;
  }

  info(msg, data) { logger.info(msg, this.sanitize(data)); }
  warn(msg, data) { logger.warn(msg, this.sanitize(data)); }
  error(msg, data) { logger.error(msg, this.sanitize(data)); }
}

Secure logging ensures Compliance with data protection regulations and prevents credential exposure in log files.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro