Files
java-ai-agents/log-anomaly/quickstart/QuickStart.java
T

65 lines
2.9 KiB
Java

// Run with: java QuickStart.java (JDK 21 or newer, no Maven, no libraries)
//
// The whole idea in one file: mask the changing parts of each log line to get a template, turn every template into
// a vector of hashed words, and measure how far a new template is from the closest "normal" one.
import java.util.*;
import java.util.regex.Pattern;
public class QuickStart {
static final Pattern NUMBER = Pattern.compile("(?<![A-Za-z])\\d+(?:\\.\\d+)?|(?<=[A-Za-z])\\d+");
/** Step 1: Order 42 placed and Order 77 placed are the same template. */
static String template(String message) {
return NUMBER.matcher(message).replaceAll("<*>");
}
/** Step 2: a template becomes a unit-length vector by hashing its words into 64 buckets. */
static double[] embed(String text) {
double[] v = new double[64];
for (String w : text.toLowerCase().split("[^a-z]+")) {
if (w.length() > 1) {
int h = w.hashCode();
v[Math.floorMod(h, 64)] += (h >>> 31) == 0 ? 1 : -1;
}
}
double norm = Math.sqrt(Arrays.stream(v).map(x -> x * x).sum());
for (int i = 0; i < v.length; i++) v[i] /= norm;
return v;
}
/** Step 3: distance = 1 - cosine similarity. 0 means the same words, 1 means no words in common. */
static double distance(double[] a, double[] b) {
double dot = 0;
for (int i = 0; i < a.length; i++) dot += a[i] * b[i];
return 1 - dot;
}
public static void main(String[] args) {
List<String> normal = List.of(
"Order 42 placed by customer c-17", "Order 43 placed by customer c-90",
"Payment approved for order 42 in 80 ms", "Payment approved for order 43 in 95 ms",
"Reserved 2 units of SKU-1001", "Token validated for user u-1001");
List<String> today = List.of(
"Order 51 placed by customer c-3",
"HikariPool-1 - Connection is not available, request timed out after 30000ms.",
"Payment approved for order 52 in 90 ms but ledger write failed");
Set<String> known = new LinkedHashSet<>();
normal.forEach(m -> known.add(template(m)));
System.out.println("normal lines: " + normal.size() + ", normal templates: " + known.size());
known.forEach(t -> System.out.println(" " + t));
Map<String, double[]> vectors = new LinkedHashMap<>();
known.forEach(t -> vectors.put(t, embed(t)));
System.out.println();
for (String line : today) {
String t = template(line);
double nearest = vectors.values().stream().mapToDouble(v -> distance(embed(t), v)).min().orElseThrow();
String verdict = known.contains(t) ? "known template" : nearest > 0.5 ? "NEW and FAR from normal" : "new but close to normal";
System.out.printf("%.3f %-24s %s%n", nearest, verdict, t);
}
}
}