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.
First obvious option is to override toString(), example:
public class Employee {
private String username;
private String password;
private String city;
@Override
public String toString() {
return "username=" + username + " city=" + city;
}
public static void main(String[] args) {
System.out.println(new Employee().toString());
}
}
You can also replace password string from logging, for example
String maskedPassword = s.replaceAll("password=[^&]*", "password=***");
In you use jersey you can add logging filter with such replacement.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With