package com.ankurm.logs; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import com.ankurm.logs.TemplateMiner.Template; /** Every figure in the post is an assertion here and a line in output/. */ class LogAnomalyTest { private final Fixtures f = new Fixtures(); @Test void parsesSpringBootLinesAndFoldsStackTraces() throws IOException { Transcript t = new Transcript("01-parse.txt", "Parsing Spring Boot log lines"); t.section("First lines of the baseline"); f.baselineLines.stream().limit(3).forEach(t::line); t.section("An ERROR with a stack trace: one event, several physical lines"); int at = f.targetLines.indexOf(f.targetLines.stream().filter(l -> l.contains("Connection is not available")).findFirst().orElseThrow()); f.targetLines.subList(at, at + 4).forEach(t::line); t.section("Counts"); t.line("baseline: %d physical lines, %d events, %d orphan lines", f.baseline.physicalLines(), f.baseline.events().size(), f.baseline.orphanLines()); t.line("target: %d physical lines, %d events, %d orphan lines", f.target.physicalLines(), f.target.events().size(), f.target.orphanLines()); LogEvent withTrace = f.target.events().stream().filter(e -> e.message().startsWith("HikariPool-1 - Connection")).findFirst().orElseThrow(); t.line("that ERROR event: level=%s logger=%s continuation lines=%d", withTrace.level(), withTrace.shortLogger(), withTrace.continuation().size()); t.line("exception line: %s", withTrace.exceptionLine()); t.section("The same line without the application name bracket"); String old = "2026-11-30T09:00:00.123+05:30 INFO 4121 --- [nio-8080-exec-1] c.a.shop.OrderController : Order 42 placed"; LogEvent e = new LogParser().parse(java.util.stream.Stream.of(old)).events().getFirst(); t.line("parsed: level=%s thread=%s logger=%s message=%s", e.level(), e.thread(), e.shortLogger(), e.message()); t.write(); assertThat(f.baseline.orphanLines()).isZero(); assertThat(f.target.physicalLines()).isGreaterThan(f.target.events().size()); assertThat(withTrace.continuation()).hasSize(3); assertThat(e.message()).isEqualTo("Order 42 placed"); } @Test void miningCollapsesThousandsOfLinesIntoTenTemplates() throws IOException { Transcript t = new Transcript("02-templates.txt", "Template mining"); t.section("Baseline: " + f.baseline.events().size() + " events become " + f.baselineTemplates.size() + " templates"); f.baselineTemplates.forEach(x -> t.line("%5d %-5s %-20s %s", x.count(), x.level(), x.logger(), x.text())); t.section("Failure: words that are not numbers. Same traffic, real user names instead of u-1042"); SyntheticLogs named = new SyntheticLogs(42, true); var events = new LogParser().parse(named.baseline(SyntheticLogs.BASELINE_START, 120).stream()).events(); TemplateMiner plain = new TemplateMiner(false, 0); long authPlain = plain.mine(events).stream().filter(x -> x.logger().equals("AuthFilter")).count(); TemplateMiner merging = new TemplateMiner(true, 8); merging.fit(events); long authMerged = merging.mine(events).stream().filter(x -> x.logger().equals("AuthFilter")).count(); t.line("AuthFilter templates, digits-only masking: %d", authPlain); t.line("AuthFilter templates, with the second pass: %d", authMerged); t.line("all templates, digits-only masking: %d", plain.mine(events).size()); t.line("all templates, with the second pass: %d", merging.mine(events).size()); merging.mine(events).stream().filter(x -> x.logger().equals("AuthFilter")).forEach(x -> t.line(" %d %s", x.count(), x.text())); t.write(); assertThat(f.baselineTemplates).hasSize(10); assertThat(authPlain).isEqualTo(20); assertThat(authMerged).isEqualTo(1); } @Test void embeddingsCompareWordsNotMeaning() throws IOException { Transcript t = new Transcript("03-embeddings.txt", "What a hashing embedder considers close (distance = 1 - cosine)"); String[][] pairs = { {"WARN PaymentService Payment declined for order <*>: insufficient funds", "INFO PaymentService Payment approved for order <*> in <*> ms"}, {"ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection", "ERROR OrderController Failed to process order <*>: validation failed"}, {"ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection", "ERROR HikariPool Could not get a database connection from the pool"}, {"INFO PaymentService Payment approved for order <*> in <*> ms", "INFO PaymentService Payment approved for order <*> in <*> ms but ledger write failed"}, {"INFO AuthFilter Token validated for user u-<*>", "ERROR HikariPool HikariPool-<*> - Connection is not available, request timed out after <*>ms."}, }; double[] d = new double[pairs.length]; for (int i = 0; i < pairs.length; i++) { d[i] = 1 - KMeans.dot(f.embedder.embed(pairs[i][0]), f.embedder.embed(pairs[i][1])); t.line("distance %.3f", d[i]).line(" A: %s", pairs[i][0]).line(" B: %s", pairs[i][1]).blank(); } t.write(); assertThat(d[0]).as("approved vs declined share most words").isLessThan(0.45); assertThat(d[2]).as("same meaning, different words").isGreaterThan(0.75); assertThat(d[2]).isGreaterThan(d[1]); assertThat(d[3]).isLessThan(0.30); assertThat(d[4]).isGreaterThan(0.9); } @Test void clusterCountDecidesWhatCountsAsNormal() throws IOException { Transcript t = new Transcript("04-clusters.txt", "k decides how far from normal a template can be"); t.section("Baseline templates grouped with k = " + Fixtures.K); int[] cluster = new int[f.baselineTemplates.size()]; for (int c = 0; c < f.model.k(); c++) { final int cc = c; t.line("cluster %d:", c); f.baselineTemplates.stream().filter(x -> f.model.clusterOf(x) == cc) .forEach(x -> t.line(" %-5s %-20s %s (distance to centre %.3f)", x.level(), x.logger(), x.text(), f.model.distance(x))); } List