Skip to lesson

Logging sensitive data

A support engineer opens the log file to chase a failed order and finds a customer's password and a full access token in plain text. Logs are read by many people and kept for months.

What must never be logged

Sensitive data in a log is any value that harms a person or the app when someone reads the log: passwords, tokens, hashes, keys and full card numbers. Some values must never appear; others only in masked form.

A login request record passed to a log call: its automatic toString() writes the password too.

Example 1 · Mistake: a record's toString prints the password

RecordToStringLeakDemo.javaJava
record LoginRequest(String email, String password) {}
public class RecordToStringLeakDemo {    public static void main(String[] args) {        LoginRequest request = new LoginRequest("asha.rao@example.com", "asha-dev-password");
        // A "harmless" debug line someone adds while fixing a login bug        System.out.println("DEBUG Login attempt: " + request);    }}
Output
DEBUG Login attempt: LoginRequest[email=asha.rao@example.com, password=asha-dev-password]

What this code does

  • Records generate toString() from all their components, so the password comes along.
  • System.out.println stands in for log.debug(...) here; a logger calls the same toString().
  • Anyone who can read the log file now knows Asha's password.

A log is the running diary an app writes: one line per event, kept in files or a log service for days or months. Developers, support staff, monitoring tools and backups can all read it, so a log is a place where secrets leak quietly. What to keep out:

  • Never: passwords, access and refresh tokens, Authorization headers, password hashes, signing keys, one-time codes.
  • Never in full: card numbers (last 4 digits at most), Aadhaar or PAN numbers, bank account numbers.
  • Personal data only when needed and masked: e-mails, phone numbers, addresses.
  • Prefer ids: user=2 tells operations enough and reveals nothing by itself.
India's Digital Personal Data Protection Act, 2023 treats such personal data as something you must protect; leaking it in logs is still a leak.

Accidental leaks: request bodies, toString and headers

A request-logging filter with bodies and headers switched on, and what the log then contains.

Example 2 · Mistake: request logging with bodies and headers

Runs in: the shoplite-api Spring Boot project (dev profile)

Java
// src/main/java/com/shoplite/common/RequestLoggingConfig.java (the mistake)@Configurationclass RequestLoggingConfig {
    @Bean    CommonsRequestLoggingFilter requestLoggingFilter() {        CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();        filter.setIncludeHeaders(true);        filter.setIncludePayload(true);        filter.setMaxPayloadLength(1000);        return filter;    }}
// application-dev.properties: logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG// and in AuthService.login: log.debug("Login attempt: {}", request);   (LoginRequest without its toString)
Sample output
2026-10-16T13:56:22.384+05:30 DEBUG 18732 --- [shoplite-api] [io-18732-exec-1] com.shoplite.auth.AuthService            : Login attempt: LoginRequest[email=asha.rao@example.com, password=asha-dev-password]
2026-10-16T13:56:24.289+05:30 DEBUG 18732 --- [shoplite-api] [io-18732-exec-1] o.s.w.f.CommonsRequestLoggingFilter      : After request [POST /api/v1/auth/login, headers=[Host:"localhost:18732", User-Agent:"curl/8.8.0", Accept:"*/*", Content-Length:"63", Content-Type:"application/json;charset=UTF-8"], payload={"email":"asha.rao@example.com","password":"asha-dev-password"}]
2026-10-16T13:56:25.136+05:30 DEBUG 18732 --- [shoplite-api] [io-18732-exec-5] o.s.w.f.CommonsRequestLoggingFilter      : Before request [GET /api/v1/me, headers=[Host:"localhost:18732", User-Agent:"curl/8.8.0", Accept:"*/*", Authorization:"Bearer eyJraWQiOiJ1ajQwRGhSendCMmM1Umh2VnctRnRYX1hWcV9ZdzNwcnI0NW55OUVHTHBnIiwiYWxnIjoiSFMyNTYifQ.eyJpc3MiOiJzaG9wbGl0ZS1hcGkiLCJjdXN0b21lcklkIjoxLCJzdWIiOiJhc2hhLnJhb0BleGFtcGxlLmNvbSIsImV4cCI6MTc5MjE0MDA4MywiaWF0IjoxNzkyMTM5MTgzLCJyb2xlcyI6WyJDVVNUT01FUiJdfQ.Oy1_NGED5PNzz0X67zQc8UQXMoyHwv0l0CCV9Rlh5Kw"]]

What this code does

  • The first line leaks the password through the record's toString(); the second leaks it again from the raw body.
  • The third line holds Asha's whole access token: copied from the log, it works for anyone until it expires.
  • The fix is to delete this filter (ShopLite does not need it). If a team wants request logs, it logs method, path, status and time only, never bodies or the Authorization header.

Most password leaks in logs are not written on purpose. A record's automatic toString() prints every field, so log.debug("Login attempt: {}", request) prints the password too, and entities and DTOs that hold tokens or hashes do the same. Request-logging filters are the other big source: Spring's CommonsRequestLoggingFilter with setIncludePayload(true) and setIncludeHeaders(true) writes every body and every header, including Authorization: Bearer .... A token in a log works for anyone who copies it until it expires.

Turning DEBUG on in production "for a few minutes" to chase a bug often switches these lines on too.

Masking values and overriding toString on records

Masking replaces most of a value with * and keeps just enough to recognise it, such as a***@example.com or a card ending in 1111. A secret such as a PIN is never shown, even in part.

A record whose toString() prints *** instead of the password, and a LogMask helper for e-mails and card numbers.

LoginRequest.javaJava
public record LoginRequest(@NotBlank String email, @NotBlank String password) {
    /** Records print every field; a login request must never print its password. */    @Override    public String toString() {        return "LoginRequest[email=" + email + ", password=***]";    }}

Example 3 · Masking helpers and a safe toString

MaskingDemo.javaJava
import java.util.List;
final class LogMask {    private LogMask() {    }
    /** "asha.rao@example.com" -> "a***@example.com" */    static String email(String email) {        if (email == null || email.isBlank()) {            return "(none)";        }        int at = email.indexOf('@');        return at <= 0 ? "***" : email.charAt(0) + "***" + email.substring(at);    }
    /** "4111111111111111" -> "************1111" */    static String cardNumber(String digits) {        if (digits == null || digits.length() < 4) {            return "****";        }        return "*".repeat(digits.length() - 4) + digits.substring(digits.length() - 4);    }}
record PaymentRequest(String email, String cardNumber, String upiPin) {    @Override    public String toString() {        return "PaymentRequest[email=" + LogMask.email(email) + ", cardNumber="                + LogMask.cardNumber(cardNumber) + ", upiPin=***]";    }}
public class MaskingDemo {    public static void main(String[] args) {        for (String e : List.of("asha.rao@example.com", "x@y.in", "not-an-email", "")) {            System.out.println(e + " -> " + LogMask.email(e));        }        PaymentRequest payment = new PaymentRequest("ravi.kumar@example.com", "4111111111111111", "1234");        System.out.println("INFO " + payment);    }}
Output
asha.rao@example.com -> a***@example.com
x@y.in -> x***@y.in
not-an-email -> ***
 -> (none)
INFO PaymentRequest[email=r***@example.com, cardNumber=************1111, upiPin=***]

What this code does

  • One helper per kind of value keeps masking the same everywhere and easy to test.
  • The record's own toString() masks its fields, so any log line that prints the object is safe.
  • A secret such as a UPI PIN is never shown even in part: *** only. (4111 1111 1111 1111 is a well-known test card number.)

Put the masking rules in one small helper (ShopLite has LogMask), so every log line masks the same way. It also makes the rules easy to test.

For a record that holds a secret, override toString() and print *** in its place. ShopLite does this for LoginRequest, SignUpRequest, TokenResponse and JwtProperties. Now even a careless log.debug("{}", request) is safe.

Fix the error

Fix the leaking log line

Read the log line it printed, then pick the line that fixes it.

Round 1 of 2

A debug line prints a login request. Fix the method that builds the text.

public record LoginRequest(String email, String password) {
@Override
public String toString() {
return "LoginRequest[email=" + email + ", password=" + password + "]";
}
}

Error

DEBUG shoplite.auth : Login attempt: LoginRequest[email=asha.rao@example.com, password=asha-dev-password]

What should be logged: security events

A security event is something operations need to see to notice an attack or answer "what happened?" later: successful and failed logins, lockouts, requests without a valid token (401) and access denials (403).

SecurityEventLog writes one line per event, with a fixed word first.

Example 4 · src/main/java/com/shoplite/common/security/SecurityEventLog.java

Runs in: the shoplite-api Spring Boot project

SecurityEventLog.javaJava
package com.shoplite.common.security;
import java.time.Duration;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;
import com.shoplite.common.LogMask;
/** * Security events, one line each, in one logger ("shoplite.security") that operations can watch. * Never a password, token, hash or full e-mail: who (user id or masked e-mail), what, from where. */@Componentpublic class SecurityEventLog {
    private static final Logger log = LoggerFactory.getLogger("shoplite.security");
    public void loginSucceeded(Integer userId, String ip) {        log.info("LOGIN_OK user={} ip={}", userId, ip);    }
    public void loginFailed(String email, String ip, int failures, int limit) {        log.warn("LOGIN_FAILED email={} ip={} failures={}/{}", LogMask.email(email), ip, failures, limit);    }
    public void loginBlocked(String email, String ip, Duration retryAfter) {        log.warn("LOGIN_BLOCKED email={} ip={} retryAfter={}s", LogMask.email(email), ip, retryAfter.toSeconds());    }
    public void unauthenticated(String method, String path, String ip) {        log.info("NO_VALID_TOKEN {} {} ip={}", method, path, ip);    }
    public void accessDenied(String method, String path, String subject, String ip) {        log.warn("ACCESS_DENIED {} {} user={} ip={}", method, path, LogMask.email(subject), ip);    }}
Sample output
2026-10-16T13:58:47.497+05:30  INFO 14660 --- [shoplite-api] [io-18731-exec-5] shoplite.security                        : LOGIN_OK user=2 ip=0:0:0:0:0:0:0:1
2026-10-16T13:58:50.537+05:30  WARN 14660 --- [shoplite-api] [io-18731-exec-8] shoplite.security                        : LOGIN_FAILED email=n***@example.com ip=0:0:0:0:0:0:0:1 failures=1/5
2026-10-16T13:58:53.847+05:30  WARN 14660 --- [shoplite-api] [o-18731-exec-10] shoplite.security                        : ACCESS_DENIED POST /api/v1/orders/14/ship user=a***@example.com ip=0:0:0:0:0:0:0:1
2026-10-16T13:58:56.787+05:30  WARN 14660 --- [shoplite-api] [io-18731-exec-2] shoplite.security                        : LOGIN_BLOCKED email=r***@example.com ip=0:0:0:0:0:0:0:1 retryAfter=899s
2026-10-16T13:58:59.266+05:30  INFO 14660 --- [shoplite-api] [io-18731-exec-5] shoplite.security                        : NO_VALID_TOKEN GET /api/v1/me ip=0:0:0:0:0:0:0:1

What this code does

  • LoginAttemptService calls the login methods; SecurityProblems (the 401 and 403 writer) calls the last two.
  • Every line starts with a fixed word, so an alert such as "more than 50 LOGIN_FAILED in a minute" is one search.
  • The lines say who, what and where, yet contain no password, token or full e-mail.

OWASP Top 10 2025 lists missing logs under A09 Logging and Alerting Failures. Log each event as one line with a fixed word first (LOGIN_FAILED, ACCESS_DENIED), then who (user id or masked e-mail), what and from where (IP).

Use one logger name, shoplite.security, so alerts and dashboards can follow just these lines.

Log levels in production, and who can read the logs

A log level says how important a log line is: ERROR, WARN, INFO, DEBUG or TRACE. A logger prints its own level and anything more important.

The prod profile: log levels and JSON log lines.

Example 5 · src/main/resources/application-prod.properties (levels and JSON logs)

Runs in: the shoplite-api Spring Boot project

Properties
# prod: the server. DB_URL, DB_USER and DB_PASSWORD must be set, or the app refuses to start.spring.datasource.hikari.maximum-pool-size=20logging.level.com.shoplite=INFO# One JSON object per log line, ready for a log collectorlogging.structured.format.console=ecsmanagement.endpoint.health.show-details=never# No API docs or Swagger UI in productionspringdoc.api-docs.enabled=falsespringdoc.swagger-ui.enabled=false
Sample output
$ java -jar target/shoplite-api-1.1.0.jar --spring.profiles.active=prod
...
{"@timestamp":"2026-10-16T08:30:06.824247600Z","log":{"level":"WARN","logger":"shoplite.security"},"process":{"pid":24908,"thread":{"name":"http-nio-18734-exec-2"}},"service":{"name":"shoplite-api","version":"1.1.0","node":{}},"message":"LOGIN_FAILED email=a***@example.com ip=0:0:0:0:0:0:0:1 failures=1/5","ecs":{"version":"8.11"}}

What this code does

  • The prod profile keeps ShopLite at INFO and never turns on DEBUG, so no request details are printed.
  • ECS (Elastic Common Schema) is one standard JSON shape for log lines; log services read log.level and log.logger directly.
  • The masked message is the same as in development; only the format changed. The time is in UTC (Z).

Production runs at INFO for ShopLite's code and WARN or INFO for libraries; DEBUG and TRACE stay off, because they print request details, SQL values and sometimes headers.

Logs are data too. Give access only to the people who need it, keep them for a fixed time (for example 90 days), and send them to a log service over HTTPS. ShopLite's prod profile writes a structured log: one JSON object per line (logging.structured.format.console=ecs), which such services can search and alert on.

Next step

Check your understanding

12 quick questions