Skip to lesson

What never to log

A log file is copied to servers, backups, log tools and support screens, and read by many people. Anything secret written there has leaked, and user text can even forge a log line.

Passwords, tokens, card numbers and personal data

Sensitive data is anything that lets someone act as a user, move money or identify a person.

Four ShopLite log lines look harmless. Find what each one leaks before you read the output.

Example 1 · Four lines that leak secrets

LeakyLogDemo.javaJava
import java.util.Map;
record LoginRequest(String email, String password) {}
record PaymentRequest(int orderId, String cardNumber, String cvv, String upiPin) {}
public class LeakyLogDemo {    static void log(String line) {        System.out.println("INFO  " + line);    }
    public static void main(String[] args) {        LoginRequest login = new LoginRequest("asha.rao@example.com", "asha-dev-password");        PaymentRequest payment = new PaymentRequest(17, "4111111111111234", "123", "4321");        Map<String, String> headers = Map.of("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI3In0.Xk2p");
        System.out.println("--- Each of these lines leaks a secret ---");        log("Login attempt: " + login);        log("Paying: " + payment);        log("Request headers: " + headers);        log("Customer created: Asha Rao, phone 9876543201, address 12 MG Road, Indiranagar");    }}
Output
--- Each of these lines leaks a secret ---
INFO  Login attempt: LoginRequest[email=asha.rao@example.com, password=asha-dev-password]
INFO  Paying: PaymentRequest[orderId=17, cardNumber=4111111111111234, cvv=123, upiPin=4321]
INFO  Request headers: {Authorization=Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI3In0.Xk2p}
INFO  Customer created: Asha Rao, phone 9876543201, address 12 MG Road, Indiranagar

What this code does

  • Nobody wrote "log the password": the record's generated toString() did it. The same happens with the card number, CVV and UPI PIN of PaymentRequest.
  • The header map holds a bearer token: anyone who reads this log can call the API as that user until the token expires. The last line writes a full phone number and home address.

In ShopLite that means passwords, JWT access and refresh tokens, Authorization headers, OTPs and UPI PINs, full card numbers and CVVs, and personal data such as full phone numbers, home addresses and e-mail addresses.

Most leaks are accidents, not choices. A record's default toString() prints every field, so log.info("Login: {}", request) writes the password. Logging whole request bodies or all headers writes tokens. India's Digital Personal Data Protection Act, 2023, and the card industry's PCI DSS rules both expect you to keep such data out of places like logs.

Fix the error

Stop the leak

Read what the log printed, then pick the safe line.

Round 1 of 2

The login line writes a secret. Which line is safe?

record LoginRequest(String email, String password) {
}
log.info("Login: {}", request);

Error

INFO Login: LoginRequest[email=asha@example.com, password=Secret#123]
The Spring Security section's lesson on logging sensitive data showed ShopLite's LogMask and SecurityEventLog. Here the focus is the habits that keep every new log line safe.

Masking values and logging ids instead of objects

Masking is hiding most of a value while keeping enough to recognise it, such as ******3201 for a phone, card ending 1234 or a***@example.com.

Masking helpers hide most of a value, and a safe toString() keeps secrets out of accidental logs. Run the demo to see both.

Example 2 · Masking helpers, a safe toString and ids instead of objects

MaskingDemo.javaJava
/** Small helpers so every class masks the same way (ShopLite keeps them in com.shoplite.common.LogMask). */final class LogMask {    private LogMask() {    }
    /** asha.rao@example.com -> a***@example.com */    static String email(String email) {        int at = email == null ? -1 : email.indexOf('@');        return at < 1 ? "***" : email.charAt(0) + "***" + email.substring(at);    }
    /** 9876543201 -> ******3201 */    static String phone(String phone) {        if (phone == null || phone.length() < 4) {            return "****";        }        return "*".repeat(phone.length() - 4) + phone.substring(phone.length() - 4);    }
    /** 4111 1111 1111 1234 -> card ending 1234 */    static String card(String number) {        String digits = number.replaceAll("[^0-9]", "");        return "card ending " + digits.substring(digits.length() - 4);    }}
record LoginRequest(String email, String password) {    @Override    public String toString() {           // the password never leaves this object by accident        return "LoginRequest[email=" + LogMask.email(email) + ", password=***]";    }}
record Customer(int id, String fullName, String phone, String address) {}
public class MaskingDemo {    static void log(String line) {        System.out.println("INFO  " + line);    }
    public static void main(String[] args) {        LoginRequest login = new LoginRequest("asha.rao@example.com", "asha-dev-password");        Customer asha = new Customer(1, "Asha Rao", "9876543201", "12 MG Road, Indiranagar");
        log("Login attempt: " + login);        log("Paid order 17 with " + LogMask.card("4111 1111 1111 1234"));        log("OTP sent to " + LogMask.phone(asha.phone()));        log("Customer " + asha.id() + " updated their address");   // the id, not the object    }}
Output
INFO  Login attempt: LoginRequest[email=a***@example.com, password=***]
INFO  Paid order 17 with card ending 1234
INFO  OTP sent to ******3201
INFO  Customer 1 updated their address

What this code does

  • LoginRequest overrides toString(), so even a careless log.info("{}", login) shows password=***. The code can still read login.password() to check it.
  • Masks keep just enough to help support staff ("which card?", "which phone?"). The address change logs only customer id 1; the address itself stays in the database.

Put the masking rules in one helper class so every service masks the same way.

Better still, log the id instead of the object: Customer 1 updated their address, not the whole Customer. The id is enough to look the rest up in the database, where access is controlled. For records that carry secrets, override toString() so an accidental log call cannot print them.

Log injection through newlines in user input

Log injection is when a user puts a line break inside their input so that, once logged, it looks like a separate, real log line.

A search box accepts any text, including line breaks. See what a raw search does to the log, then what escaping does.

Example 3 · A fake log line from a search box

LogInjectionDemo.javaJava
public class LogInjectionDemo {    static void log(String level, String requestId, String message) {        System.out.println(level + " [" + requestId + "] " + message);    }
    /** Makes line breaks and tabs visible, and keeps user text short. */    static String safe(String userText) {        String oneLine = userText.replace("\r", "\\r").replace("\n", "\\n").replace("\t", "\\t");        return oneLine.length() > 80 ? oneLine.substring(0, 80) + "..." : oneLine;    }
    public static void main(String[] args) {        String search = "shoes\nINFO  [a1f3] Refund of Rs 50000 approved for order 12 by admin";
        System.out.println("--- Raw user input: a fake line appears ---");        log("INFO ", "c9d1", "Product search: " + search);
        System.out.println("--- Sanitised: still one line ---");        log("INFO ", "c9d1", "Product search: " + safe(search));    }}
Output
--- Raw user input: a fake line appears ---
INFO  [c9d1] Product search: shoes
INFO  [a1f3] Refund of Rs 50000 approved for order 12 by admin
--- Sanitised: still one line ---
INFO  [c9d1] Product search: shoes\nINFO  [a1f3] Refund of Rs 50000 approved for order 12 by admin

What this code does

  • Logged raw, the line break in the search text produced a second line that looks exactly like a real refund approval, even with a believable request id.
  • safe() turns line breaks into the visible text \n and cuts long input, so the user's text always stays inside one line of yours.

A search for shoes followed by a fake INFO ... Refund of Rs 50000 approved line can fool whoever reads the log later, or a tool that parses it.

Never log user text raw. Replace \r and \n with visible escapes, cut long values, and validate ids before using them, as the request id filter did. JSON (structured) logs escape line breaks inside fields, which is one more reason to use them on servers.

Predict the output

How many log lines?

The user typed pen, a line break, then WARN Refund approved.

Round 1 of 2

The app logs the text raw. What does the log file hold?

String text = "pen\nWARN Refund approved";
log.info("Search: " + text);

Too much logging: noise, cost and disk space

One busy sale day can produce millions of lines. The demo below counts what chatty logging costs.

Example 4 · What chatty logging costs

LogVolumeDemo.javaJava
public class LogVolumeDemo {    static final int REQUESTS_PER_DAY = 400_000;   // a small online shop during a sale    static final int BYTES_PER_LINE = 220;          // a typical line with timestamp, ids and message
    static double gbPerDay(int linesPerRequest) {        double bytes = (double) REQUESTS_PER_DAY * linesPerRequest * BYTES_PER_LINE;        return bytes / (1024 * 1024 * 1024);    }
    static void show(String setting, int linesPerRequest) {        System.out.printf("%-37s %3d lines/request -> %5.2f GB/day, %6.1f GB/month%n",                setting, linesPerRequest, gbPerDay(linesPerRequest), gbPerDay(linesPerRequest) * 30);    }
    public static void main(String[] args) {        show("INFO: one summary line per request", 1);        show("INFO: chatty services", 6);        show("DEBUG left on in production", 40);        show("DEBUG + full request/response bodies", 120);    }}
Output
INFO: one summary line per request      1 lines/request ->  0.08 GB/day,    2.5 GB/month
INFO: chatty services                   6 lines/request ->  0.49 GB/day,   14.8 GB/month
DEBUG left on in production            40 lines/request ->  3.28 GB/day,   98.3 GB/month
DEBUG + full request/response bodies  120 lines/request ->  9.83 GB/day,  295.0 GB/month

What this code does

  • A simplified model (every line 220 bytes), but the shape is real: a forgotten DEBUG level turns 2.5 GB a month into about 100 GB, and logging bodies makes it far worse.
  • Log services usually charge by the gigabyte, and every extra line also slows down search during an incident.

More logging is not more safety. Every line costs disk, network, money in a paid log service and the reader's attention. A real error buried among millions of DEBUG lines is as hidden as an error never logged.

Keep production at INFO, log one summary line per request instead of one line per step, and never log whole request or response bodies. When the same warning repeats hundreds of times a minute, log it once with a count of the skipped lines.

Next step

Check your understanding

10 quick questions