Files
java-ai-agents/log-anomaly/src/main/java/com/ankurm/logs/TemplateMiner.java
T

135 lines
5.4 KiB
Java

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.
*
* <p>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("(?<![A-Za-z])\\d+(?:\\.\\d+)?|(?<=[A-Za-z])\\d+");
/** One template and how often it was seen. */
public record Template(String level, String logger, String text, int count, String example) {
/** The string that is embedded: the level and class name carry meaning, so they travel with the text. */
public String embeddingText() {
return level + " " + logger + " " + text;
}
public String key() {
return level + "|" + logger + "|" + text;
}
}
private final boolean mergeVaryingWords;
private final int maxDistinct;
/** Learned by {@link #fit}: for each group, which word positions are wildcards. */
private final Map<String, boolean[]> 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<LogEvent> baseline) {
wildcards.clear();
if (!mergeVaryingWords) {
return;
}
Map<String, List<String[]>> groups = new LinkedHashMap<>();
Set<String> seen = new HashSet<>();
for (LogEvent e : baseline) {
String masked = mask(e.message());
if (seen.add(e.level() + "|" + e.shortLogger() + "|" + masked)) {
String[] w = masked.split(" ");
groups.computeIfAbsent(group(e.level(), e.shortLogger(), w), k -> new ArrayList<>()).add(w);
}
}
groups.forEach((g, list) -> {
int len = list.getFirst().length;
boolean[] wild = new boolean[len];
boolean any = false;
for (int pos = 0; pos < len; pos++) {
final int p = pos;
wild[pos] = list.stream().map(w -> w[p]).distinct().count() > maxDistinct;
any |= wild[pos];
}
if (any) {
wildcards.put(g, wild);
}
});
}
/** Counts events per (level, logger, template), most frequent first. */
public List<Template> mine(List<LogEvent> events) {
Map<String, int[]> counts = new LinkedHashMap<>();
Map<String, LogEvent> examples = new HashMap<>();
for (LogEvent e : events) {
String key = keyOf(e);
counts.computeIfAbsent(key, k -> new int[1])[0]++;
examples.putIfAbsent(key, e);
}
List<Template> out = new ArrayList<>();
counts.forEach((k, c) -> {
String[] p = k.split("\\|", 3);
out.add(new Template(p[0], p[1], p[2], c[0], examples.get(k).message()));
});
out.sort((a, b) -> Integer.compare(b.count(), a.count()));
return out;
}
}