Developer reviewing structured application logs with sensitive values hidden

Editorial illustration; it does not show a real application or customer data.

Published on October 21, 2026.

When production breaks at 2:00 a.m., your first question is “What actually happened?” A clean timestamp, request ID, route, and error class turn a vague user complaint into a bug you can reproduce in five minutes.

The trouble is how easy it is to over-log while chasing that clarity. A developer dumps the entire request body during a tricky integration, logs a payment gateway payload for convenience, or lets a framework exception serialiser print an Authorization header. Six months later, an archived log bucket holds a plaintext copy of customer emails, NRICs, session cookies, and API keys that nobody ever meant to store there.

Good logging is not about recording everything. It is about recording just enough context to diagnose an incident while treating log storage as part of your security boundary.

Start with incident questions, not print dumps

“Log everything just in case” is not an observability strategy; it is a liability. Before adding a log call, decide which operational question it answers:

  • Did the request reach the application or fail at the proxy?
  • Which route, controller, or background worker failed?
  • Was the failure caused by input validation, an upstream dependency, or a timeout?
  • Did one account hit an edge case, or is the whole service degrading?

Notice that none of those questions require a customer’s full name, home address, or raw JSON payload. If your database already holds the user profile, the log only needs a stable internal reference (account_ref or invoice_id) so an authorised engineer can correlate the event.

Use structured events with an explicit allow-list

Structured JSON logs are far easier to query with jq, Loki, or Elasticsearch than free-form prose, and they force you to name the exact fields you intend to keep:

{
  "event": "invoice_generation_failed",
  "request_id": "req_7f3c",
  "invoice_id": "inv_2048",
  "account_ref": "acct_91a2",
  "dependency": "pdf-service",
  "error_class": "timeout",
  "duration_ms": 3100
}

Keep your field names and error categories consistent. Having timeout, timed_out, and PDF service took too long across three endpoints makes dashboards and alerts brittle.

The most common leak happens when someone logs an entire framework object:

// Dangerous: captures Authorization headers, cookies, passwords, and unexpected client fields
logger.info("incoming request", { headers: req.headers, body: req.body });

In ASP.NET Core or Serilog, the same trap happens with destructuring ({@Model}) on a DTO that happens to include Password, Token, or IcNumber. Instead of relying on a block-list that breaks the day someone adds a new field named secret_note, build an allow-list of safe metadata:

logger.info("incoming request", {
  event: "request_received",
  request_id: requestId,
  method: req.method,
  route: routeName,
  content_length: req.headers["content-length"]
});

If you ever need deep payload inspection for a stubborn bug, enable it behind a short-lived, scoped feature flag with an owner and expiry—and remember that deleting the log line in code does not purge historical lines already shipped to central log storage or backups.

Choose between omitting, masking, hashing, and truncating

Different fields call for different handling:

  • Omit anything unnecessary for triage. A password-reset log needs event, request_id, and outcome—never the reset link or token.
  • Mask values when support staff only need to recognise shape, such as the last four digits of a card if policy permits. Even masked emails (a***@example.com) can still count as personal data under privacy rules, so treat them carefully.
  • Hash stable identifiers with a keyed HMAC when you need to count unique actors without storing raw values. A plain unsalted SHA-256 hash of a phone number or email is trivial to reverse via rainbow tables.
  • Truncate and sanitise user-supplied strings and third-party error messages. Long payloads bloat storage, and unescaped newlines let a malicious input forge fake log lines (log injection).

Make failure paths as informative as success paths

Teams often log rich details when a checkout succeeds and then log "Something went wrong" when it fails. Flip that habit. Failure events should carry a safe reason code, dependency name, retry attempt number, and correlation ID.

Keep raw stack traces server-side behind access controls, and return only a generic message plus the request_id to the user. That way, a customer can paste req_7f3c into a support ticket without you ever exposing internal file paths or database errors in the browser. For background jobs that retry automatically, log the attempt number and reserve high-severity alerts for final exhaustion rather than paging on-call for every transient blip.

Lock down the proxy and log pipeline too

Application code is only half the story. Reverse proxies and web servers happily leak secrets before your app even runs if you put tokens in query strings.

In Nginx, for example, the default $request variable logs the full URI including ?token=... or ?api_key=.... If your app ever receives sensitive parameters in URLs, avoid putting them in query strings altogether—and configure your access log format to log $uri instead of $request_uri where appropriate, or strip sensitive query parameters.

Just as important is retention. Logs that live forever quietly become an unindexed shadow database. Set explicit expiry rules at the infrastructure layer—for example, MaxRetentionSec=30day in /etc/systemd/journald.conf or rotate 14 with compression in /etc/logrotate.d/—and restrict who can query production logs. Add an automated redaction test to your CI pipeline: send a fake bearer token, password-shaped string, and sample NRIC/email through your error handlers, and assert that none of those strings appear in the emitted log output.

A quick pre-merge log check

Before merging a PR that adds new logging, run through a fast mental check: what incident question does this event answer, is every field explicitly allow-listed, are secrets and raw PII absent across both success and failure paths, and will high-volume traffic turn this line into a storage or rate-limit problem?

If you inherit a legacy app with noisy, leaky logs, do not try to rewrite every logger in one sprint. Pick the five events your team searches most often during incidents, strip obvious secrets, add request_id correlation, standardise the field names, and verify that your next debugging session is both faster and safer.

For related engineering workflows, see stopping unfinished features from mixing in Git, resolving merge conflicts safely, and finding frontend bugs with browser DevTools.

Sources