Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

A security audit finds personal data and tokens in logs, mostly coming from toString output of DTOs, records and exceptions. What standards and library support do you introduce across services?

Generated toString methods, from records, Lombok and IDEs, print every field, so sensitive values leak whenever an object is logged or put into an exception message. I would fix it at the source with a shared wrapper type (or an annotation the shared toString support honours) that masks sensitive values, add masking rules in the log encoders only as a second line of defence, add tests and static checks that fail when sensitive fields are printed, and treat log data itself as sensitive, with retention limits and access controls.

Why this question is asked

Log files are one of the most common places personal data and credentials leak from, and the leak is rarely a deliberate log.info(password). It is a DTO printed in full by a generated toString, or an exception message that includes the request object, multiplied across dozens of services. When an audit finds this, we need a fix that works for every team and keeps working as new classes are added. Interviewers ask this design question to see whether we can find the root cause in the language and libraries, choose layered defences and make them enforceable. In this answer, we will trace how sensitive data reaches the logs, then go through the fix at the source, the masking layer in the encoders, the tests and checks that keep it fixed, and the controls on the logs themselves.

1How Sensitive Data Reaches the Logs

Three features that are good for productivity combine to cause the problem. Records generate a toString that prints every component. Lombok's @Data and @ToString do the same for every field. IDE-generated toString methods include all fields by default too. Each of them is written once, and when someone later adds a token or a date of birth to the class, it silently joins the output.

Then that output travels. Parameterised logging calls toString on every argument, string concatenation does it in exception messages, and frameworks log request bodies or failed objects in their error handling. Exceptions are the sneaky path: a validation error built as new IllegalArgumentException("invalid: " + request) puts the whole request into the message, and the message is then logged by a global handler, often in another team's code.

Java
record PaymentRequest(String cardNumber, String cvv, String email, long amountCents) {}
throw new IllegalArgumentException("invalid payment: " + request);
// ERROR invalid payment: PaymentRequest[cardNumber=4111111111111111, cvv=123,
// email=ana@example.com, amountCents=1500]

2Fix at the Source: A Shared Sensitive Type

The strongest fix makes the value itself safe to print, so it does not matter which toString, exception or framework touches it. We publish a small type in a shared library and require sensitive fields to use it.

Java
public final class Sensitive<T> {
private final T value;
private Sensitive(T value) { this.value = Objects.requireNonNull(value); }
public static <T> Sensitive<T> of(T value) { return new Sensitive<>(value); }
public T reveal() { return value; } // explicit, searchable access
@Override public String toString() { return "***"; }
}
record PaymentRequest(Sensitive<String> cardNumber, Sensitive<String> cvv,
Sensitive<String> email, long amountCents) {}
log.error("invalid payment: {}", request);
// invalid payment: PaymentRequest[cardNumber=***, cvv=***, email=***, amountCents=1500]

The reason a type works better than a convention is that it travels with the value. The masked toString applies inside records, collections, exception messages and debuggers, without anyone remembering. The method name reveal() makes every real use visible in code review and easy to search for. The type also needs a deliberate serializer configuration in Jackson, so that APIs which must send the value do so on purpose and the default is masked.

Where changing field types is too disruptive, the alternative is an annotation such as @Sensitive on fields, combined with shared toString support that honours it: Lombok's @ToString.Exclude, or a hand-written toString in records. That is weaker, because each class must still be written correctly, so the type is the target and the annotation is the transition.

3Second Line: Masking Rules in the Log Encoders

We also configure the logging layer to mask patterns that look sensitive, such as card numbers, bearer tokens and email addresses, before log events are written. Logback and Log4j 2 can replace text matching a regular expression in the formatted message, and JSON encoders for both have masking features for named fields (check your encoder's documentation for the exact configuration).

XML
<!-- logback.xml, pattern layout: mask 13 to 19 digit runs and bearer tokens -->
<pattern>%d %level %logger - %replace(%replace(%msg){'\b\d{13,19}\b','[card]'}){'Bearer [A-Za-z0-9._-]+','Bearer [token]'}%n</pattern>
Step throughLayers of defence for sensitive data in logs
  1. Sensitive typemasks itself in every toString and exception
  2. Generated toString rulesno @Data on sensitive classes; records override
  3. Tests and static checksfail the build when sensitive fields are printed
  4. Encoder maskingregex and field rules catch what slips through
  5. Log access and retentionlimits the damage when something still leaks

5 layers, from the top down. Step through them one at a time.

Each layer assumes the one above it will sometimes fail.

This catches data that slips past the type, such as a token printed by a third-party library. But it must stay the second line, not the only one. A regular expression cannot recognise a name or an address, it misses values split across fields or encoded, it costs CPU on every log line, and it gives false confidence. Masking at the source is precise; masking at the encoder is a net.

4Tests and Static Checks That Keep It Fixed

Rules that depend on memory decay as teams change, so we add checks to the shared build. An architecture test, for example with ArchUnit, fails when a field whose name suggests a secret, such as password, token, secret, cvv or cardNumber, has a type other than Sensitive. A canary test goes further: an integration test sends requests containing unique marker values and asserts that no captured log line contains them.

Java
@Test void noSensitiveValuesInLogs(CapturedOutput output) { // Spring Boot's OutputCaptureExtension
client.post("/payments", request("4111111111111111", "CANARY-CVV-7731", "canary@example.test"));
assertThat(output.getAll())
.doesNotContain("4111111111111111")
.doesNotContain("CANARY-CVV-7731")
.doesNotContain("canary@example.test");
}

Notice that the canary test checks the behaviour we care about, what actually reaches the logs, through every path, including global exception handlers and framework logging. It catches leaks that no field-level rule could predict. Each service runs it for its main endpoints, and the shared test starter makes it a few lines to write.

5Treating Logs as Sensitive Data

Even with every layer in place, some sensitive data will reach logs eventually, so the logs themselves need protection proportionate to that risk. That means a retention limit, for example 30 days for application logs instead of indefinite storage, access controlled by role and audited, encryption at rest, and a rule that production logs are not pasted into tickets or chat.

There is also a regulatory reason. Data protection rules give people rights over their personal data, such as deletion, and logs are a poor place to honour those rights. Keeping personal data out of logs, and keeping logs only as long as they are useful, makes compliance tractable.

6Rolling It Out Across Services

I would start with the audit's findings: fix the classes it named, then add the Sensitive type and the canary test to the shared starter and adopt them in the services that handle payments, authentication and customer data first. The architecture rule starts in reporting mode with a baseline of existing violations and becomes blocking for new code after a month. The encoder masking is enabled centrally in the shared logging configuration, so every service gets the net on the next upgrade.

Success is measured by the next audit and, in between, by a scheduled scan of stored logs for the same patterns the encoder masks: the number of hits should fall to near zero and stay there.

7Follow-up questions

Why not simply forbid logging of DTOs?

It helps, and logging identifiers instead of objects is a good habit, but it cannot be enforced across exception messages, framework error handlers and third-party libraries. A rule about how values print protects all those paths at once, which a rule about where to log cannot.

Is char[] for passwords still worth using?

It lets us clear the password from memory after use, which matters in some threat models, and an array's toString prints only a type and hash, so it does not leak the contents in logs. But frameworks convert to String anyway in many places, so for log safety the masking type is more effective; char[] addresses a different risk.

How do you handle sensitive data inside exception messages from libraries?

Catch at the boundary, translate to our own exception with a safe message, and log the original exception's type and a correlation ID rather than its message when it may contain input. The encoder masking layer is the safety net for library messages we do not control.

8Conclusion

In this answer, we saw that generated toString methods print every field, and that exceptions and logging spread that output. The fix starts at the source with a shared Sensitive type, or an annotation honoured by shared toString support, adds masking in log encoders as a second line of defence, enforces the rule with architecture tests and canary tests that search logs for marker values, and treats the logs themselves as sensitive with retention and access controls.

What to say in the interviewAbout 80 seconds aloud

Open with

The root cause is that records, Lombok and IDE-generated toString methods print every field by default, and that output flows into logs through parameterised logging, exception messages and framework error handlers.

Then, if they want more

So I would fix it at the source first: a small shared type, say Sensitive of T, whose toString returns stars and whose value is only available through an explicit reveal() method, and require it for passwords, tokens, card data and personal data in DTOs and records.

Because the masking travels with the value, it works in collections, exceptions and debuggers. Where changing types is too disruptive, a @Sensitive annotation honoured by shared toString support is the transition.

Second, I would configure masking in the log encoders, regexes for card numbers and bearer tokens and field rules for JSON logs, but explicitly as a net, not the main control.

Third, enforcement: an ArchUnit rule that fields named like password or token must use the type, and a canary integration test that sends unique marker values and asserts they never appear in captured logs. And finally, treat logs as sensitive data: short retention, role-based audited access, and no production logs pasted into tickets.

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 documentation below. 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 security audit finds personal data and tokens in logs, mostly coming from toString...": https://scrivio-interview-library.netlify.app/java/object-contracts/d8d932101e/