Mask certain string attributes in Java during logging?

Viewed 3858

Is there a way I can mask certain string variables of a class like password, etc which will prevent during logging? Like overriding toString() method in such way it does not print in logs.

For instance, we have a class Employee with following fields:

public class Employee {
    private String username;
    **private String password; //mask this field**
    private String city;
}

During logging like

LOGGER.INFO("printing object:"+employee);

Here in logging, I'm trying to print the whole object, Employee here and my requirement is it does not print out masked field, password at all and whereas logging of rest of the fields are fine.

3 Answers

If you are using lombok, try the exclude option for ToString.

@Data
@ToString(exclude = {"password"})
public class Employee {
    private String username;
    private String password;
    private String city;
}
Related