Skip to main content

Sensitive data in logs: tokens, PII and the logger nobody reviews

Application logs are a second database that nobody designed. They hold request headers, error payloads, upstream responses and whatever a developer printed while chasing a bug at midnight. They are copied to a log platform, retained for months, searchable by a wide group of engineers, and exported to more places than the primary database ever is.

That makes a token or a password in a log line an incident with a long tail. This post covers where sensitive values enter logs, how to remove them at the logger rather than at each call site, and what retention and access rules make the remaining risk acceptable.

Why it matters more than it looks

Writing sensitive data to a log is its own weakness class, CWE-532, and the OWASP Logging Cheat Sheet lists what should usually not be recorded directly: session identifiers, access tokens, authentication passwords, database connection strings, encryption keys, payment card data and sensitive personal data. Logging also has its own category in the OWASP Top 10:2025, A09 Security Logging and Alerting Failures.

Regulators treat plaintext credentials in internal systems as a security failure, not a housekeeping issue. In September 2024 Ireland's Data Protection Commission fined Meta 91 million euro after an inquiry that began when the company reported storing some user passwords in plaintext on internal systems. Logs are one of the easiest ways for plaintext secrets to end up in internal systems, because nobody designs them as a store of secrets.

Where secrets enter logs

Source What leaks
Request logging middleware Authorization and Cookie headers, whole request bodies with passwords and card numbers
Error handlers and error trackers Request data attached to exceptions, local variables in stack frames
Upstream response logging OAuth token responses, payment provider replies, API keys echoed back
URL logging Tokens in query strings: password reset links, signed URLs, ?api_key=
ORM and query logs Bound parameter values, including password hashes and personal data
Debug statements print(user) or console.log(req.body) that survived review
Prompt and model logs Prompts that carry customer records into an LLM call

The pattern behind most of these is logging a whole object. logger.info(req.body) is fine on the day it is written and wrong the day someone adds a password field to the form.

Fix 1: log fields you choose, not objects

Structured logging makes the safe version easy. Log an explicit set of fields:

// Wrong: every current and future field of the body
logger.info({ body: req.body }, "signup");

// Right: the fields you need to debug signups
logger.info({ userId: user.id, plan: req.body.plan, ip: req.ip }, "signup");

An allowlist of fields ages well. A blocklist of "bad" field names misses the new one, pwd, secret_answer or ssn_last4, that nobody added to the list.

Fix 2: redact at the logger

Some values will reach the logger anyway, through middleware, libraries and exception handlers you did not write. Redact there, once. In Node, pino supports path-based redaction:

const pino = require("pino");

const logger = pino({
  redact: {
    paths: [
      "req.headers.authorization",
      "req.headers.cookie",
      "*.password",
      "*.token",
      "*.apiKey",
    ],
    censor: "[REDACTED]",
  },
});

In Python, a filter on the handler sees every record that reaches it, including records from third-party loggers that propagate to the root:

import logging
import re

PATTERNS = [
    (re.compile(r"(?i)\b(bearer)\s+[A-Za-z0-9._~+/=-]+"), r"\1 [REDACTED]"),
    (re.compile(r"(?i)\b(password|passwd|secret|token|api_key)=([^&\s]+)"), r"\1=[REDACTED]"),
    (re.compile(r"\b\d{13,19}\b"), "[CARD?]"),
]

class RedactFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        message = record.getMessage()
        for pattern, replacement in PATTERNS:
            message = pattern.sub(replacement, message)
        record.msg, record.args = message, None
        return True

handler = logging.StreamHandler()
handler.addFilter(RedactFilter())
logging.basicConfig(level=logging.INFO, handlers=[handler])

Attach it to the handler, not to one logger: Python applies logger-level filters only to records created on that logger, while handler filters see everything the handler writes. The filter formats the message first, so values passed as %s arguments are redacted too.

Pattern redaction is a safety net, not the main control. It catches bearer tokens and key=value pairs; it cannot recognise a name or an address. Fix 1 does the real work.

Fix 3: configure the error tracker

Error tracking SDKs capture request data, headers, cookies and sometimes local variables by default or by one option. Read your SDK's documentation for its personal data option and its before-send hook, set the first deliberately, and use the second to strip headers and bodies:

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  beforeSend(event) {
    if (event.request) {
      delete event.request.cookies;
      delete event.request.data;
      if (event.request.headers) delete event.request.headers.authorization;
    }
    return event;
  },
});

Fix 4: keep tokens out of URLs

Anything in a URL lands in access logs, proxy logs, browser history and Referer headers. Send API keys in a header, put password reset tokens in a link that is exchanged for a session on first use, and give signed URLs short lifetimes. If you must accept a token in a query string, strip it in the access log format.

Retention and access

Redaction lowers what is in the logs. Retention and access decide how long the rest is exposed and to whom.

  • Set retention by purpose. Debug logs rarely need more than a few weeks. Security and audit logs often need longer, and may be required by your compliance framework. Keep them in separate streams so you can treat them differently.
  • Restrict who can search. Production log search is a data access path. Grant it like database read access, and log the searches.
  • Plan for deletion. If a secret does reach logs, you need to find and purge it across the platform, its archives and any exports. Practise once before you need it.
  • Rotate what leaked. A token that reached a log is compromised for planning purposes. Deleting the line is not enough; revoke and reissue it.

A review checklist

  • No logger.*(req.body), logger.*(req.headers) or logger.*(user) style calls on whole objects.
  • Request logging middleware redacts Authorization, Cookie and Set-Cookie.
  • Upstream HTTP clients do not log response bodies from auth, payment or token endpoints.
  • The error tracker strips request bodies, cookies and auth headers.
  • No secrets in query strings, or the access log format drops them.
  • Secret-named environment variables are never printed at startup.
  • Retention is set per stream, and log search access is reviewed.

What Vulkro checks

Vulkro Core reports sensitive values written to logs in JavaScript, TypeScript, Python, Go and Java. In Go and Java, log-secret-name flags a credential, secret or personal-data shaped value reaching a log call (password, token, apiKey, authorization, ssn, cvv and similar, including getters such as getPassword()), log-whole-object flags a whole request, payload or user object being logged, and log-env-secret flags a secret-named environment variable being printed. In JavaScript, TypeScript and Python the logging checks flag the same shapes, plus logged authorization headers and request bodies, and pii-whole-object-dump flags whole objects carrying personal data. auth-credential-on-logger-line and stored-credential-in-response cover credentials in log lines and responses, and leak-002-prompt-in-log covers prompts written to logs. In JavaScript, TypeScript and Python it also reports a Sentry initialisation with no before-send scrubbing, and a redaction library in the project lowers the confidence of pattern-only log findings.

Log injection is a separate problem (forged log lines from CR and LF in input), reported as js-taint-log-001, py-taint-log-001 and their Go and Java equivalents.

vulkro scan .
vulkro dataflow . --sensitive   # flows that carry personal data, including into logs

FAQ

Should I hash or mask values in logs?

Mask values you never need, such as passwords and full card numbers: they should not appear at all. Hash identifiers you need to correlate, such as a session id, so you can follow one session through the logs without storing the value that grants access to it.

Is it enough to redact in the log platform?

No. Redacting after ingestion leaves the value in transit, in the agent's buffer and in any other destination the logs were shipped to. Redact in the process that writes the log, and treat platform-side scrubbing as a second layer.

What should I do if a token is already in the logs?

Revoke and reissue the token first, then purge the log entries from the platform, archives and exports. Then find the code path that logged it and fix that, or the next deployment logs the new token.

See the compliance evidence use case and the secrets detection reference, or start a 14-day trial. Related: rotating a leaked secret and HIPAA and application code.