Course contentsShow
← Security
Lesson 1354 of 3,05227. Application Security - Secrets ManagementFree lesson

Preventing Secrets in Logs and Error Messages

Learn techniques to sanitize logs, redact sensitive values, and prevent secrets from appearing in stack traces or debug output.

Preventing Secrets in Logs and Error Messages

What you'll learn: How to sanitize logs and error output to prevent secrets from being accidentally exposed in debugging information or stack traces.

The Problem

Even when you've secured secret storage and implemented scanning tools, your application can still leak secrets through logs, error messages, and stack traces. When developers log variables "for debugging," write detailed error messages, or allow frameworks to dump full stack traces, sensitive values like API keys, passwords, and tokens can end up in log files, monitoring systems, or even user-facing error pages.

How Secrets Leak Into Logs

Secrets appear in logs through several common patterns:

  • Debug logging that dumps request/response bodies or variable values
  • Exception stack traces that include method parameters containing secrets
  • Framework defaults that log all HTTP headers or environment variables
  • Error messages that echo back user input or configuration values

Prevention Techniques

Sanitize before logging: Create wrapper functions or middleware that automatically redact known secret patterns (bearer tokens, password fields, API keys) before any logging occurs.

Configure framework logging: Most logging frameworks support field exclusion lists. Configure them to skip fields named password, token, secret, apiKey, etc.

Structure your logs: Use structured logging (JSON format) so you can programmatically filter fields. Never log raw objects or dictionaries without sanitization.

Catch and sanitize exceptions: Implement global exception handlers that strip sensitive parameters from stack traces before they're logged or displayed.

Think of it like a hospital's privacy protocol—even when discussing a patient's case internally, sensitive identifiers are redacted from all documentation.

Key Takeaway: Logs and error messages are often overlooked attack surfaces; implement automatic sanitization at every logging point to ensure secrets never appear in debug output, even during incidents.