Pushing commit for BAEL-4999
This commit is contained in:
parent
9df4fd7d75
commit
26038deef8
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.logback;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import ch.qos.logback.classic.PatternLayout;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
|
||||
public class MaskingPatternLayout extends PatternLayout {
|
||||
|
||||
private Pattern multilinePattern;
|
||||
private List<String> maskPatterns = new ArrayList<>();
|
||||
|
||||
// invoked for every single entry in the xml
|
||||
public void addMaskPattern(String maskPattern) {
|
||||
maskPatterns.add(maskPattern);
|
||||
multilinePattern = Pattern.compile(maskPatterns.stream().collect(Collectors.joining("|")), Pattern.MULTILINE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String doLayout(ILoggingEvent event) {
|
||||
return maskMessage(super.doLayout(event));
|
||||
}
|
||||
|
||||
private String maskMessage(String message) {
|
||||
if (multilinePattern == null) {
|
||||
return message;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(message);
|
||||
Matcher matcher = multilinePattern.matcher(sb);
|
||||
while (matcher.find()) {
|
||||
IntStream.rangeClosed(1, matcher.groupCount()).forEach(group -> {
|
||||
if (matcher.group(group) != null) {
|
||||
// replace each character with asterisk
|
||||
IntStream.range(matcher.start(group), matcher.end(group)).forEach(i -> sb.setCharAt(i, '*'));
|
||||
}
|
||||
});
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.logback;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class MaskingPatternLayoutExample {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MaskingPatternLayoutExample.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
Map<String, String> user = new HashMap<String, String>();
|
||||
user.put("user_id", "87656");
|
||||
user.put("SSN", "786445563");
|
||||
user.put("address", "22 Street");
|
||||
user.put("city", "Chicago");
|
||||
user.put("Country", "U.S.");
|
||||
user.put("ip_address", "192.168.1.1");
|
||||
user.put("email_id", "spring@baeldung.com");
|
||||
JSONObject userDetails = new JSONObject(user);
|
||||
|
||||
logger.info("MaskingPatternExample log from {}" + userDetails,
|
||||
MaskingPatternLayoutExample.class.getSimpleName());
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue