package com.ankurm.logs; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Turns thousands of log lines into a few dozen templates by replacing the parts that change (ids, numbers, IPs) * with {@code <*>}. {@code Order 42 placed} and {@code Order 77 placed} are the same template. * *
Pass 1 masks anything that looks like an identifier or a number. Pass 2 (optional) handles words that vary
* but contain no digit, such as user names: inside a group of templates that share a logger, level, length and
* first two words, a position holding more than {@code maxDistinct} different words is also made a wildcard.
* This is a small cousin of the Drain parse tree, not a replacement for it.
*/
public final class TemplateMiner {
public static final String WILDCARD = "<*>";
private static final Pattern UUID = Pattern.compile("\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b");
private static final Pattern IPV4 = Pattern.compile("\\b\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d+)?\\b");
private static final Pattern HEX = Pattern.compile("\\b0x[0-9a-fA-F]+\\b");
private static final Pattern NUMBER = Pattern.compile("(? wildcards = new HashMap<>();
public TemplateMiner(boolean mergeVaryingWords, int maxDistinct) {
this.mergeVaryingWords = mergeVaryingWords;
this.maxDistinct = maxDistinct;
}
/** Pass 1 only: digits and identifiers masked. */
public static String mask(String message) {
String s = UUID.matcher(message).replaceAll(WILDCARD);
s = IPV4.matcher(s).replaceAll(WILDCARD);
s = HEX.matcher(s).replaceAll(WILDCARD);
return NUMBER.matcher(s).replaceAll(WILDCARD);
}
private static String group(String level, String logger, String[] w) {
return level + "|" + logger + "|" + w.length + "|" + w[0] + " " + (w.length > 1 ? w[1] : "");
}
/** The template text of one event: pass 1, then the pass-2 wildcards learned by {@link #fit}. */
public String templateOf(LogEvent e) {
String masked = mask(e.message());
if (wildcards.isEmpty()) {
return masked;
}
String[] w = masked.split(" ");
boolean[] wild = wildcards.get(group(e.level(), e.shortLogger(), w));
if (wild == null) {
return masked;
}
for (int i = 0; i < w.length; i++) {
if (wild[i]) {
w[i] = WILDCARD;
}
}
return String.join(" ", w);
}
/** The key a detector uses to compare events: level, class, template. */
public String keyOf(LogEvent e) {
return e.level() + "|" + e.shortLogger() + "|" + templateOf(e);
}
/** Learns pass-2 wildcards from a baseline window. Does nothing when pass 2 is off. */
public void fit(List