|
| 1 | +package org.tron.common.logsfilter; |
| 2 | + |
| 3 | +import ch.qos.logback.classic.pattern.ClassicConverter; |
| 4 | +import ch.qos.logback.classic.spi.ILoggingEvent; |
| 5 | +import com.google.common.cache.Cache; |
| 6 | +import com.google.common.cache.CacheBuilder; |
| 7 | +import java.util.regex.Matcher; |
| 8 | +import java.util.regex.Pattern; |
| 9 | +import lombok.extern.slf4j.Slf4j; |
| 10 | +import org.tron.core.config.args.Args; |
| 11 | + |
| 12 | +@Slf4j(topic = "Parser") |
| 13 | +public class DesensitizedConverter extends ClassicConverter { |
| 14 | + |
| 15 | + private static final int SENSITIVE_WORD_SIZE = 1_000; |
| 16 | + |
| 17 | + private static final Pattern pattern = Pattern.compile( |
| 18 | + "/(((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|" |
| 19 | + + "([1-9]?\\d))))"); |
| 20 | + |
| 21 | + private static final Cache<String, String> sensitiveCache = CacheBuilder.newBuilder() |
| 22 | + .maximumSize(SENSITIVE_WORD_SIZE) |
| 23 | + .recordStats().build(); |
| 24 | + |
| 25 | + public static void addSensitive(String key, String value) { |
| 26 | + sensitiveCache.put(key, value); |
| 27 | + } |
| 28 | + |
| 29 | + public String desensitization(String content) { |
| 30 | + if (sensitiveCache.size() > 0) { |
| 31 | + Matcher matcher = pattern.matcher(content); |
| 32 | + while (matcher.find()) { |
| 33 | + String key = matcher.group(); |
| 34 | + String value = sensitiveCache.getIfPresent(key); |
| 35 | + if (value != null) { |
| 36 | + content = content.replaceAll(key, value); |
| 37 | + } else { |
| 38 | + content = content.replaceAll(key, "unknown"); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + return content; |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + public String convert(ILoggingEvent iLoggingEvent) { |
| 47 | + String source = iLoggingEvent.getFormattedMessage(); |
| 48 | + return Args.getInstance().isFastForward() ? desensitization(source) : source; |
| 49 | + } |
| 50 | +} |
0 commit comments