logback 日志脱敏
1. 继承MessageConverter,重写convert方法
public class SensitiveDataConverter extends MessageConverter {
@Override
public String convert(ILoggingEvent event) {
// 获取原始日志
String oriLogMsg = event.getFormattedMessage();
//todo 获取脱敏后的日志
String afterLogMsg = "";
return afterLogMsg;
}
}
2. 修改xml配置文件,添加conversionRule标签,指定上面的SensitiveDataConverter类
<configuration>
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 -->
<property name="LOG_HOME" value="./logs"/>
<!--配置日志转换规则-->
<conversionRule conversionWord="msg" converterClass="com.hfepay.common.log.config.SensitiveDataConverter"> </conversionRule>
...
</configuration>
log4j2 日志脱敏
1. 继承LogEventPatternConverter,重写format方法。加@Plugin 和 @ConverterKeys 注解
@Plugin(
name = "SensitiveDataConverter",
category = "Converter"
)
//自定义重写的属性
@ConverterKeys({"coverMsg"})
public class SensitiveDataConverter extends LogEventPatternConverter {
protected SensitiveDataConverter(String name, String style) {
super(name, style);
}
public static SensitiveDataConverter newInstance(String[] options) {
return new SensitiveDataConverter("coverMsg", "coverMsg");
}
@Override
public void format(LogEvent logEvent, StringBuilder stringBuilder) {
// 获取原始日志
String oriLogMsg = logEvent.getMessage().getFormattedMessage();
//todo 获取脱敏后的日志
String afterLogMsg = "";
stringBuilder.append(afterLogMsg);
}
}
2. 修改xml配置文件把原先PatternLayout标签里的pattern属性中的msg改成coverMsg
<!--修改前的-->
<PatternLayout charset="UTF-8" pattern="%d{yyyy-MM-dd HH:mm:ss.SSS}|%-5level|%traceId|%thread|%logger:%line|%msg%n"/>
<!--修改后的-->
<PatternLayout charset="UTF-8" pattern="%d{yyyy-MM-dd HH:mm:ss.SSS}|%-5level|%traceId|%thread|%logger:%line|%coverMsg%n"/>