我目前将 Log4J 用于库,并希望转向使用 SLF4J 以允许库的用户选择日志框架。
除了我用来在日志消息进入屏幕或日志之前替换日志消息中的文本的一类之外,一切都很好:
public class FilteringLayout extends PatternLayout {
private static final String REPLACEMENT = "[APIKEY]";
private static Pattern replacementPattern = Pattern.compile("DO_NOT_MATCH");
public static void addReplacementString(String replacementString) {
replacementPattern = Pattern.compile(replacementString);
}
@Override
public String format(LoggingEvent event) {
if (event.getMessage() instanceof String) {
String message = event.getRenderedMessage();
Matcher matcher = replacementPattern.matcher(message);
if (matcher.find()) {
String maskedMessage = matcher.replaceAll(REPLACEMENT);
Throwable throwable = event.getThrowableInformation() != null
? event.getThrowableInformation().getThrowable() : null;
LoggingEvent maskedEvent = new LoggingEvent(event.fqnOfCategoryClass,
LoggerFactory.getLogger(event.getLoggerName()), event.timeStamp,
event.getLevel(), maskedMessage, throwable);
return super.format(maskedEvent);
}
}
return super.format(event);
}
}
我将如何使用纯 SLF4J 做到这一点并消除对 Log4J 的依赖?
编辑:为了更清楚起见,我想在将其发送到下游记录器之前自动从日志消息中删除一组字符序列。