log4j2日志脱敏

文章介绍了如何在resource目录下创建log4j2.component.properties文件,用于配置自定义的日志事件工厂FuzzLogEventFactory。这个工厂类实现了LogEventFactory接口,主要功能是通过正则表达式匹配并模糊处理电子邮件地址,以保护日志中的敏感信息。在检测到邮箱格式时,使用`@`符号前的两个字符进行星号(*)替换,达到日志脱敏的效果。文章还包括了错误处理逻辑,当处理日志时发生异常,会记录错误信息。
摘要由CSDN通过智能技术生成

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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值