Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lombok Conditional ToString.Include

Tags:

java

lombok

Lombok supports the @ToString.Include to allow custom formatting of an attribute when printing the Object or attribute. I'm considering using this feature to mask PII data when logging to a log file. I still want to include the field in the log but I need it to be masked. However, adding this annotation always masks the field. Is there a way to make this conditional? The issue I'm having is that when debugging, the field is masked. I'd really like the field to be masked only when I indicate it should be masked i.e. when logging to a log file.

like image 938
Mike Avatar asked Jan 21 '26 10:01

Mike


1 Answers

After experimenting with this, I'm happy with the way this is working. My main concern was that I would lose the ability to view the attribute values while debugging. That is not the case of course. When I log the object it applies the toString function for the object and masks the attributes I want to mask. But I can still view the attribute values in the object.

As an example, if I set emailAddress = [email protected] I can print an EmailAddress Object and it will print EmailAddress(emailAddress=t********@gmail.com)

@Builder
@Getter
@EqualsAndHashCode
@ToString
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public final class EmailAddress {
    private final String emailAddress;

    // replace all characters after the first character with a *
    // up to the @ symbol
    @ToString.Include(name = "emailAddress")
    private String fieldMasker() {
        return emailAddress.replaceAll("(?<=.{1}).(?=[^@]*?@)", "*");
    }
}
like image 194
Mike Avatar answered Jan 22 '26 23:01

Mike