log4j2日志脱敏

  • Post author:
  • Post category:其他


resource下建文件,文件名:log4j2.component.properties

log4j2.component.properties 文件写入:Log4jLogEventFactory = com.xx.xx.xx.FuzzLogEventFactory

写FuzzLogEventFactory:

public interface Constants {
    /**
     * 邮箱正则
     */
    String EMAIL_RGX = "[a-z\\dA-Z]+[- | a-z\\dA-Z . _]+@([a-z\\dA-Z]+(-[a-z\\dA-Z]+)?\\.)+[a-z]{2,}";

}


/**
 * 邮箱日志脱敏
 **/
public class FuzzLogEventFactory implements LogEventFactory {
    /**
     * regex 分组
     */
    private static final String MASK_REGEX = "(\\S+)(\\S{2})(@.*)";
    private Pattern emailPattern = Pattern.compile(EMAIL_RGX);
    private static final FuzzLogEventFactory instance = new FuzzLogEventFactory();

    public static FuzzLogEventFactory getInstance() {
        return instance;
    }


    public LogEvent createEvent(String loggerName, Marker marker, String fqcn, Level level,
                                Message message, List<Property> properties, Throwable throwable) {

        String formattedMessage = message.getFormattedMessage();
        String fuzzedMsg = fuzzIfNecessary(emailPattern, formattedMessage);
        Message handledMsg = new SimpleMessage(fuzzedMsg);
        return new Log4jLogEvent(loggerName, marker, fqcn, level, handledMsg, properties, throwable);
    }

    private String fuzz(String sensitiveData) {
        //@符前二个字符*化
        return sensitiveData.replaceAll(MASK_REGEX, "$1**$3");
    }

    private String fuzzIfNecessary(Pattern pattern, String formattedMsg) {
        StringBuffer sb = new StringBuffer();
        try {
            Matcher matcher = pattern.matcher(formattedMsg);
            while (matcher.find()) {
                String original = matcher.group();
                if (!Objects.isNull(original)) {
                    String fuzzed = fuzz(original);
                    matcher.appendReplacement(sb, fuzzed);
                }
            }
            if (sb.length() != 0) {
                matcher.appendTail(sb);
                return sb.toString();
            }
        } catch (Exception e) {
            StatusLogger.getLogger().error(
                    "fuzzLogEventFactory fuzz msg:{} raise error", formattedMsg, e);
        }
        return formattedMsg;
    }



版权声明:本文为qianhuan_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。