简体   繁体   English

在日志记录期间屏蔽 Java 中的某些字符串属性?

[英]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.就像以这种方式覆盖toString()方法一样,它不会在日志中打印。

For instance, we have a class Employee with following fields:例如,我们有一个具有以下字段的类 Employee:

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

During logging like在记录期间像

LOGGER.INFO("printing object:"+employee); LOGGER.INFO("打印对象:"+员工);

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.在日志记录中,我试图打印整个对象, Employee 在这里,我的要求是它根本不打印屏蔽字段,密码,而其余字段的日志记录很好。

First obvious option is to override toString(), example:第一个明显的选择是覆盖 toString(),例如:

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.在您使用 jersey 时,您可以使用此类替换添加日志过滤器

Create a class called MaskedString that is basically just a replacement for String but has a toString method that doesn't output the actual password:创建一个名为 MaskedString 的类,它基本上只是 String 的替代品,但有一个不输出实际密码的 toString 方法:

public class MaskedString(){
    private String maskedString;

    MaskedString(){
        maskedString = "";
    }

    MaskedString(String string){
        maskedString = string;
    }

    public String getActualString(){
        return maskedString;
    }

    public String setString(String string){
        maskedString = string;
    }

    public String toString(){
        return "Not the actual string!";
    }
}

If you are using lombok , try the exclude option for ToString.如果您使用lombok ,请尝试 ToString 的 exclude 选项。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM