Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask certain string attributes in Java during logging?

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.

like image 710
Vinod Kumar Avatar asked Jul 14 '26 10:07

Vinod Kumar


2 Answers

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.

like image 50
user7294900 Avatar answered Jul 15 '26 22:07

user7294900


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;
}
like image 36
Vinto Avatar answered Jul 15 '26 23:07

Vinto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!