Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

A developer logs log.info("Creating customer {}", customer) and the Customer class's toString() includes email, phone and card number. Show at least three ways to stop sensitive data from reaching the logs, and say which one you prefer.

The best fix is not to log the object at all and log only its identifier, for example log.info("Creating customer {}", customer.id()). Other ways are overriding toString to leave out or mask sensitive fields (explicitly for records, or with Lombok's @ToString.Exclude), using value types such as a CardNumber whose toString prints only the last four digits, and adding a masking layer in the encoder as a safety net. I prefer identifiers plus safe value types, because they fix the problem by design, and keep regex masking only as the last line of defence.

Why this question is asked

Logging a whole object is one of the most common ways personal and card data ends up in logs, and once it is there it is copied to every system the logs flow into. It is also easy to do by accident: the developer wrote a harmless-looking line, and the leak comes from a toString() written somewhere else, maybe generated by a record or by Lombok. Interviewers ask this coding question to see whether we fix the cause or only the symptom. In this answer, we will reproduce the leak, then work through four fixes from the most to the least preferable, show the code for each, and finish with how to test that sensitive fields never reach the output.

1Reproducing the Leak

Here is the situation. Customer is a record, and records generate a toString() that prints every component. SLF4J calls toString() when it formats the {} placeholder.

Java
record Customer(long id, String name, String email, String phone, String cardNumber) {}
Customer c = new Customer(42, "Asha Rao", "asha@example.com", "+44 7700 900123", "4111111111111111");
log.info("Creating customer {}", c);
// INFO Creating customer Customer[id=42, name=Asha Rao, email=asha@example.com,
// phone=+44 7700 900123, cardNumber=4111111111111111]

Notice that nothing in the log statement mentions email or card numbers. The leak is invisible in code review of this line, which is why we want fixes that work wherever the object is logged.

2Fix 1: Log the Identifier, Not the Object

The simplest and most reliable fix is to log what we actually need. To follow a customer's journey through the logs, the id is enough; anyone who needs more can look the customer up in the system that is meant to hold that data, with its access controls.

Java
log.info("Creating customer {}", c.id());
// INFO Creating customer 42
// with structured logging, the id becomes a searchable field
log.atInfo().setMessage("Creating customer").addKeyValue("customerId", c.id()).log();
// {"message":"Creating customer","customerId":42, ...}

This is the fix I prefer, and I would make it the team's habit: log identifiers and states, not domain objects. Its weakness is that it depends on every developer remembering it, so the next fixes make the objects themselves safe.

3Fix 2: A Safe toString

If the object is logged, its toString() should be safe. For a record that means overriding toString() explicitly, since the generated one prints every component. With Lombok, @ToString.Exclude leaves a field out of the generated method.

Java
record Customer(long id, String name, String email, String phone, String cardNumber) {
@Override public String toString() {
return "Customer[id=" + id + ", email=" + mask(email) + "]";
}
private static String mask(String e) { return e.charAt(0) + "***@" + e.substring(e.indexOf('@') + 1); }
}
log.info("Creating customer {}", c);
// INFO Creating customer Customer[id=42, email=a***@example.com]
// Lombok class
@ToString
class CustomerEntity {
Long id;
@ToString.Exclude String email;
@ToString.Exclude String cardNumber;
}
// CustomerEntity(id=42)

But there is a catch: toString() is also used in debuggers and error messages, and a later developer may add a new sensitive field and forget to exclude it. An explicit allow list, printing only named safe fields as in the record above, ages better than an exclude list.

4Fix 3: Value Types That Cannot Leak

A stronger design moves the protection into the type of the sensitive value itself. If the card number is a CardNumber object rather than a String, its toString() can print only the last four digits, and every object that contains it, every log line and every exception message that prints it, is safe automatically.

Java
record CardNumber(String value) {
CardNumber { if (!value.matches("\\d{12,19}")) throw new IllegalArgumentException("invalid card number"); }
@Override public String toString() { return "****" + value.substring(value.length() - 4); }
}
record Email(String value) {
@Override public String toString() { return "[email]"; }
}
record Customer(long id, String name, Email email, String phone, CardNumber card) {}
log.info("Creating customer {}", c);
// INFO Creating customer Customer[id=42, name=Asha Rao, email=[email], phone=+44 7700 900123, card=****1111]
The four approaches
ApproachProtectsWeakness
Log identifiers onlyevery line written this wayrelies on habit
Safe toStringevery place the object is printednew fields may be forgotten
Safe value typesevery object holding the valueneeds type changes in the model
Masking in the encoderall output, as a safety netcosts CPU, misses unknown formats

Now the card and email are safe even with the generated record toString(). The name and phone in this example would need the same treatment, which shows why this works best combined with Fix 1. Notice also that the exception message for an invalid card does not include the value.

5Fix 4: A Masking Layer in the Encoder

As a safety net for anything the first three fixes miss, the logging pipeline can mask known patterns before writing. With logstash-logback-encoder, MaskingJsonGeneratorDecorator masks fields by name or values by regular expression. With a plain Logback pattern, the %replace conversion word or a custom converter does the same, and in Log4j2 a rewrite policy or a %replace pattern can be used.

XML
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<jsonGeneratorDecorator class="net.logstash.logback.mask.MaskingJsonGeneratorDecorator">
<defaultMask>****</defaultMask>
<path>password</path> <!-- any field named password -->
<value>\b\d{13,19}\b</value> <!-- card-like digit runs -->
<value>[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[a-z]{2,}</value> <!-- email addresses -->
</jsonGeneratorDecorator>
</encoder>
// message: "Creating customer Customer[id=42, ..., email=****, ..., cardNumber=****]"

I treat this as the last line of defence, not the main fix. Running several regular expressions over every event costs CPU on busy services, and patterns miss formats they were not written for, such as a card number with spaces or a phone number in an unusual format. It catches mistakes; it does not replace design.

6Follow-up questions

How would you test that sensitive fields never reach the log output?

Write a test that logs realistic objects through the real logging configuration and asserts on the captured output. In Spring Boot, OutputCaptureExtension gives the console output of a test, so we can call the service method that logs, then assert that the output does not contain the test email or card number and does contain the masked form. A unit test on each value type's toString() and a test that builds every domain object with known sensitive values and checks its toString() catch regressions when fields are added. In CI, scanning the logs of the integration test run for card-like numbers that pass a Luhn check adds another net.

Is masking in the encoder enough for PCI DSS?

It helps, but relying on it alone is weak, because a pattern can miss a format and the card number has still been processed in memory and possibly in exception messages. The stronger position is that card numbers never reach logging code at all, through value types and logging identifiers, with encoder masking and log scanning as detection and safety layers. Check the current PCI DSS requirements with your security team for the exact obligations.

Does logging at DEBUG instead of INFO solve the problem?

No. DEBUG gets switched on during incidents, which is exactly when the data is copied into the logs, and nobody remembers to clean it up. Sensitive data rules apply to every level.

7Conclusion

In this answer, we reproduced a leak caused by a record's generated toString() and fixed it in four ways. Logging identifiers only is the preferred habit, a safe toString() with an explicit allow list protects every place the object is printed, value types such as CardNumber make the sensitive value itself safe everywhere, and a masking layer in the encoder, such as MaskingJsonGeneratorDecorator, a custom converter or a Log4j2 rewrite policy, is the safety net. Regex masking costs CPU and misses formats, so it supports design rather than replacing it.

What to say in the interviewAbout 90 seconds aloud

Open with

The line itself looks harmless, the problem is that SLF4J calls toString, and the Customer's toString prints email, phone and the card number. If Customer is a record, the generated toString prints every component.

Then, if they want more

My preferred fix is simply not to log the object: log the id, like Creating customer {} with customer.id(), or as a structured field. Debugging needs identifiers, and anyone who needs the details can look them up in the system built for that data.

Second, I'd make the toString safe: override it explicitly in the record to print only allowed fields, or with Lombok use ToString.Exclude on the sensitive fields, though an allow list ages better because new fields aren't printed by accident.

Third, and I like this one a lot, value types: a CardNumber type whose toString prints only the last four digits, an Email type that prints a placeholder. Then every object, log line or exception that prints them is safe automatically.

Fourth, as a safety net, masking in the encoder: with logstash-logback-encoder the MaskingJsonGeneratorDecorator masks fields by name and values by regex, and in Log4j2 a rewrite policy or replace pattern does the same. I'd treat regex masking as the last line of defence, since it costs CPU and misses formats.

And I'd add a test with OutputCapture asserting the test card number never appears in the output.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A developer logs log.info("Creating customer {}", customer) and the Customer class's...": https://scrivio-interview-library.netlify.app/java/java-logging/a73d920485/