grep for ERROR, find forty, and cannot tell which of the forty is new.
The question underneath is simple: which messages in this log are unlike the messages we normally see? That is a question a computer can answer by turning each message into a list of numbers (an embedding), measuring distances, and grouping the normal ones (clustering). This article builds that pipeline in plain Java for a Spring Boot application, runs it on a log with a planted incident, and — more usefully — measures where it fails.
The failures are the point. An anomaly detector that is demonstrated only on the incident it was built for is a magic trick. Here the same run also shows a real bug it misses, a harmless deployment it flags, and a number it can never see. If you only remember one thing: distance from normal is a good way to rank log messages and a poor way to decide which of them is a page.
Verified against. Spring Boot 4.2.0 (on Maven Central since 2026-11-19, the date in maven-metadata.xml), JDK 25 LTS, JUnit 6.1.3. No Spring AI and no model download: the embedder and the summariser are interfaces, and every transcript below comes from an offline run. The logs are synthetic (a seeded generator, described below), except one file written by a real Spring Boot 4.2.0 process. A real embedding model and a real chat model were not run; the two classes that call them were tested against stub HTTP servers only.
What does “unusual” mean for a log line?
A log line such asOrder 77525 placed by customer c-519 total=8093.82 is unique as text but ordinary as a kind of message. Replace the parts that change with a wildcard and you get Order <*> placed by customer c-<*> total=<*>, a template. A healthy application writes a small, stable set of templates. An unhealthy one starts writing templates it has never written, or writes familiar ones far too often.
That gives two separate questions, and the rest of the article is built on keeping them separate:
- Is this template new, and is it far from every normal template? (novel-template detection, which needs the embeddings and clusters.)
- Is this familiar template arriving much faster than usual? (rate-spike detection, which needs only counting.)
Going deeper: why not just alert on every new template?
A new template is the cheapest possible signal: a set lookup. It is also noisy, because every deployment that rewords a log message creates one. The embedding earns its place by ranking new templates, so a reworded INFO line sorts below a new connection-pool error. Whether the ranking is trustworthy enough to act on is the subject of the blind-spots section, where it is measured on a deliberately awkward example.The usual alternatives are worth knowing by name: Drain (and the Logpai benchmark family) for template parsing, DeepLog-style sequence models that predict the next template, and plain rate alerts in your metrics system. This article does not compare against them; it measures one pipeline honestly.
The smallest version: one file, no libraries
Before any Spring Boot, here is the whole idea in a single Java file. It masks numbers to get templates, hashes the words of each template into a 64-slot vector, and prints how far each of today’s lines is from the closest normal template. You can run it withjava QuickStart.java on JDK 21 or newer (the same single-file launcher trick as in the JBang article, minus JBang). Download QuickStart.java or read it in the repository: quickstart/QuickStart.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);
}
}
}
Its output, copied from output/00-quickstart.txt:
$ java QuickStart.java
normal lines: 6, normal templates: 4
Order <*> placed by customer c-<*>
Payment approved for order <*> in <*> ms
Reserved <*> units of SKU-<*>
Token validated for user u-<*>
0.000 known template Order <*> placed by customer c-<*>
0.764 NEW and FAR from normal HikariPool-<*> - Connection is not available, request timed out after <*>ms.
0.225 new but close to normal Payment approved for order <*> in <*> ms but ledger write failed
Three things to notice. Six normal lines became four templates, so counting templates already compresses. A line that has been seen before has distance 0.000. And the connection-pool error scores 0.764 while the payment line that merely gained a clause scores 0.225: distance measures how many words are new, which is a different thing from how bad the news is. That sentence is the plot of the rest of the article.
Going deeper: what the 64-slot hash is doing
Each word is turned into a number withString.hashCode(), the number picks one of 64 slots, and the top bit picks a plus or minus sign, so two unrelated words that land in the same slot tend to cancel instead of adding up. This is the “hashing trick”. The vector is then divided by its own length so that every vector has length 1, which makes the dot product of two vectors their cosine similarity, and 1 - cosine the distance used everywhere below. The module uses the same idea with 256 slots and also hashes neighbouring word pairs.It knows nothing about meaning. “Connection refused” and “could not connect” share no words, so they are far apart. That is the limit a real embedding model removes, and the section on swapping the embedder shows where it plugs in.
Step one: read the log Spring Boot actually writes
The first job is boring and decides everything after it: turning text lines into events. Spring Boot’s default layout is a timestamp, a padded level, a process id,---, an optional bracketed application name, the thread in brackets, the logger name and a message. A stack trace follows as extra lines that start with nothing recognisable. If you treat each physical line as an event, one exception becomes forty events and every count later in the pipeline is wrong.
The rule is one regular expression and one decision: a line that starts with a timestamp opens a new event, and any other line belongs to the previous event (LogParser.java).
private static final Pattern HEADER = Pattern.compile(
"^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}(?:Z|[+-]\\d{2}:\\d{2}))\\s+([A-Z]+)\\s+\\d+\\s+---\\s+"
+ "(?:\\[[^\\]]*]\\s+)?\\[([^\\]]*)]\\s+(\\S+)\\s+:\\s(.*)$");
I did not want to trust a regular expression that was tested only on text I generated, so one test starts a real Spring Boot 4.2.0 application with spring.application.name=shop, lets it write its own log file, logs an exception, and parses the result (RealSpringBootLogTest.java). From output/12-real-spring-boot-log.txt:
2026-12-01T23:53:38.561+05:30 ERROR 12412 --- [shop] [main] com.ankurm.shop.OrderController : Failed to process order 42
java.lang.IllegalStateException: quantity must be greater than 0
at com.ankurm.logs.RealSpringBootLogTest.theParserReadsWhatSpringBootActuallyWrites(RealSpringBootLogTest.java:23) ~[test-classes/:na]
Look at the line between the message and the exception: Spring Boot 4.2.0 writes an empty line before a stack trace. My first version of exceptionLine() took the first continuation line, got an empty string, and failed the test; the fix is to skip blank lines. It is a small thing, and it is the kind of thing a parser written from memory gets wrong.
A parser that drops lines is worse than no parser. The first transcript counts lines on purpose: 3,947 physical lines became 3,857 events, with 0 orphan lines (lines before the first timestamp). If that last number is not zero on your own logs, your layout differs from the default and every later number is suspect. Check it before anything else.The counts, from output/01-parse.txt:
baseline: 3947 physical lines, 3857 events, 0 orphan lines
target: 2196 physical lines, 1524 events, 0 orphan lines
Going deeper: layouts, correlation ids and JSON logs
The pattern accepts the default layout with or without the application name bracket; in the 4.2.0 runs above the bracket is present whenspring.application.name is set (I saw it absent in the console output of the endpoint test, which sets no name). If you set a custom logging.pattern.console, add a correlation id, or log JSON with logging.structured.format.console, this regular expression is the one thing you must change. With structured JSON logs you skip the parsing problem entirely and read the message field, which is a good reason to prefer them if you are starting fresh.Multi-line messages that are not exceptions (a pretty-printed payload, say) have the same shape as a stack trace and are folded into the previous event the same way, which is usually what you want.
Step two: ten sentences instead of 3,857 lines
Now shrink the data. TemplateMiner.java replaces numbers and identifiers with<*>. The rule is two regular-expression alternatives: a number that does not follow a letter, and a number that does (so SKU-1004, c-519 and HikariPool-1 all lose their numbers but keep their hyphen).
private static final Pattern NUMBER = Pattern.compile("(?<![A-Za-z])\\d+(?:\\.\\d+)?|(?<=[A-Za-z])\\d+");
Applied to the two-hour baseline it gives ten templates. They are in output/02-templates.txt:
791 INFO CatalogController GET /api/products/<*> <*> in <*> ms
746 INFO AuthFilter Token validated for user u-<*>
715 INFO OrderController Order <*> placed by customer c-<*> total=<*>
695 INFO InventoryService Reserved <*> units of SKU-<*>
653 INFO PaymentService Payment approved for order <*> in <*> ms
120 INFO HikariPool HikariPool-<*> - Pool stats (total=<*>, active=<*>, idle=<*>, waiting=<*>)
62 WARN PaymentService Payment declined for order <*>: insufficient funds
43 WARN SlowQueryDetector Slow query (<*> ms): select * from orders where customer_id = ?
30 ERROR OrderController Failed to process order <*>: validation failed
2 INFO CacheRefresher Nightly cache refresh completed in <*> ms
ERROR for a failed validation appears 30 times in two hours, so the model has seen an error before and will not treat “ERROR” as a strange word. If your baseline window contained no errors at all, every real error would look alien and the detector would be useless; choose a baseline that includes a normal amount of trouble.
Going deeper: when words vary but are not numbers
Numbers are easy because a regular expression can find them. User names, tenant names and product titles vary without a digit, and masking by pattern misses them. In the test I regenerated the same traffic with real user names (alice, bob and eighteen more) instead of u-1042. Digits-only masking then produced 20 templates for the one authentication line, and 29 templates overall instead of 10. Each name became its own template, so each name looked like a new kind of message.The module has an optional second pass: inside a group of templates that share a logger, a level, a length and their first two words, a word position that holds more than eight different values becomes a wildcard too. With it the authentication line is one template again and the total is back to 10. It is a crude cousin of the Drain parse tree and it has a cost: two genuinely different messages that happen to share a shape can be merged. Use a real log parser such as Drain3 (the Logpai Drain implementation) if your logs are not this regular.
AuthFilter templates, digits-only masking: 20
AuthFilter templates, with the second pass: 1
all templates, digits-only masking: 29
all templates, with the second pass: 10
746 Token validated for user <*>
Step three: what “close” means to an embedder
An embedding turns text into a vector so that similar text gets similar vectors. The module defines the seam as an interface with one real method (Embedder.java) and ships a word-hashing implementation with no model and no network. Each template is embedded together with its level and class name, soERROR HikariPool ... and INFO AuthFilter ... start far apart before the message text is even compared.
Distance is one minus the cosine of the angle between two vectors: 0 for the same words, 1 for no words in common. Here is what that does to four of the five pairs in the transcript, from output/03-embeddings.txt:
distance 0.415
A: WARN PaymentService Payment declined for order <*>: insufficient funds
B: INFO PaymentService Payment approved for order <*> in <*> ms
distance 0.249
A: ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection
B: ERROR OrderController Failed to process order <*>: validation failed
distance 0.853
A: ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection
B: ERROR HikariPool Could not get a database connection from the pool
distance 0.118
A: INFO PaymentService Payment approved for order <*> in <*> ms
B: INFO PaymentService Payment approved for order <*> in <*> ms but ledger write failed
The first pair is the uncomfortable one: “Payment declined” and “Payment approved” are opposites, and sit 0.415 apart. The second pair, an unrelated validation error and a JDBC error from the same method, are 0.249 apart. The third pair means the same thing in different words (a pool error described two ways) and are 0.853 apart. The fourth is a normal line and the same line with “but ledger write failed” appended, and it is 0.118 apart — closer than anything else on the list.
Distance is lexical here, and probably only partly semantic with a real model. A hashing embedder compares words. A trained embedding model compares something closer to meaning, so it should pull the third pair together. It will not make “approved” and “declined” opposites in any way a cosine can use, and it will not know that a ledger failure is worse than a latency figure. I did not run a real model for this article, so I cannot give you its numbers; the next paragraph shows exactly where one plugs in.
Going deeper: swapping in a real embedding model
OpenAiCompatibleEmbedder calls any POST /v1/embeddings endpoint with the OpenAI request shape (OpenAI, Ollama, vLLM, LM Studio), batches 64 texts per request, normalises the result and refuses a vector whose length is not the configured one. In the test it talks to a stub server that returns the hashing embedder’s own vectors, which proves the plumbing and nothing about a real model’s quality. The transcript (output/08-embedder-swap.txt) shows two requests for the whole run: one for the ten baseline templates, one for the new one.embedder: openai-compatible:stub-model, dimensions: 32
HTTP requests while fitting 10 baseline templates: 2
first request body: {"model":"stub-model","input":["INFO CatalogController GET /api/products/<*> <*> in <*> ms","INFO AuthFilter Token validated for user u-<*>","INFO Ord...The dimension check is there because a model change that silently changes the vector length would make every old centroid meaningless. The stub returns 3 numbers where 32 were configured:configured dimensions: 32, stub returned 3
error: expected 32 dimensions but the model returned 3Two practical consequences if you do swap: embed templates, never raw lines (ten texts instead of four thousand, which is the difference between a free run and a billed one), and refit the baseline whenever you change the model, because vectors from two models cannot be compared.
Step four: group the normal templates, and decide how far is too far
Ten templates in one big heap are not a useful picture of normal. Clustering groups them so that “normal” becomes a handful of centres, and a new template’s distance is measured to the nearest centre. The module uses spherical k-means (vectors and centres have length 1, closest means highest cosine) with a fixed starting point, so the same input always gives the same clusters (KMeans.java). The distance itself is a few lines (BaselineModel.java): public double distance(Template t) {
float[] v = embedder.embed(t.embeddingText());
int c = KMeans.nearest(v, clusters.centroids());
return Math.max(0.0, 1.0 - KMeans.dot(v, clusters.centroids()));
}
With k = 4 the ten baseline templates fall into the four groups below. They are output/04-clusters.txt, trimmed:
cluster 0:
INFO CatalogController GET /api/products/<*> <*> in <*> ms (distance to centre 0.325)
INFO InventoryService Reserved <*> units of SKU-<*> (distance to centre 0.325)
INFO CacheRefresher Nightly cache refresh completed in <*> ms (distance to centre 0.321)
cluster 1:
INFO OrderController Order <*> placed by customer c-<*> total=<*> (distance to centre 0.343)
INFO PaymentService Payment approved for order <*> in <*> ms (distance to centre 0.212)
WARN PaymentService Payment declined for order <*>: insufficient funds (distance to centre 0.315)
ERROR OrderController Failed to process order <*>: validation failed (distance to centre 0.339)
cluster 2:
INFO AuthFilter Token validated for user u-<*> (distance to centre 0.239)
INFO HikariPool HikariPool-<*> - Pool stats (total=<*>, active=<*>, idle=<*>, waiting=<*>) (distance to centre 0.239)
cluster 3:
WARN SlowQueryDetector Slow query (<*> ms): select * from orders where customer_id = ? (distance to centre 0.000)
Each group is plausible: the catalogue, inventory and cache-refresh lines share their word shape, the payment and order lines share theirs. The threshold is then learned from the baseline: the worst-fitting normal template is 0.343 from its centre, so I flag a new template only if it is more than 0.05 beyond that, which is 0.393. The 0.05 is my choice, not a law, and the next table shows how much depends on it.
The same file also sweeps k (the asterisk marks a template flagged at that row’s threshold), in output/04-clusters.txt:
k worst-normal threshold | hikari jdbc gateway reword ledger-fail
1 0.677 0.727 | 0.747* 0.629 0.623 0.470 0.368
2 0.564 0.614 | 0.726* 0.477 0.471 0.410 0.305
4 0.343 0.393 | 0.678* 0.434* 0.459* 0.394* 0.256
10 0.000 0.050 | 0.510* 0.249* 0.401* 0.101* 0.118*
(* = flagged at that threshold)
Read the rows as a story about k. With k = 1 the single centre is the average of everything, so even normal templates are far from it (worst 0.677); the threshold climbs to 0.727 and only the pool timeout gets through. With k = 10 every baseline template is its own centre, normal templates are at distance 0, the threshold collapses to the 0.05 margin, and all five new templates are flagged, including the harmless reword and the ledger failure. k = 4 is in between, and I chose it up front, not by an optimisation. If your baseline has hundreds of templates you will want a principled choice (silhouette score, or the elbow of the within-cluster distance), which this module does not implement.
Going deeper: what k-means is and is not doing for you
With only ten baseline templates, k-means is more ceremony than necessity: nearest-neighbour distance (that is, k = 10) is simpler and flagged the most templates of the four rows. Clustering pays when there are hundreds or thousands of templates, because it turns “compare with every template” into “compare with a few centres” and, more importantly, gives each region of normal behaviour a name you can show a person.Two details of the implementation matter if you adapt it. The starting centres are chosen farthest-first from the first vector, so there is no random seed and no flaky test, at the cost of being sensitive to which template comes first. And the centres are unit vectors, so the distance to a centre is not the distance to the closest member; a template can be closer to a member than to the centre of the member’s own cluster, which is what makes the “reword” line (0.394 from its centre, much nearer than that to its sibling) look worse than it is.
Run it on an incident
The target window is 30 minutes of the same shop with three planted events. From minute 5 a deployment rewords the order message (harmless). From minute 12 the connection pool starts timing out, which produces new ERROR templates, a new gateway-timeout warning, and a surge of declined payments. double floor = Math.max(base[1], 0.5); // a template that never varied must not give a std of 0
int peak = 0;
int peakBucket = 0;
for (int i = 0; i < counts.length; i++) {
if (counts[i] > peak) {
peak = counts[i];
peakBucket = i;
}
}
double z = (peak - base[0]) / floor;
if (peak >= minCount && z > sigma) {
The floor exists because a template that was perfectly steady in the baseline has a standard deviation of 0, and dividing by 0 would flag anything. The result, from output/05-detection.txt:
threshold 0.393 (worst baseline distance 0.343 + margin 0.05), k = 4
## Flagged
NOVEL_TEMPLATE ERROR HikariPool HikariPool-<*> - Connection is not available, request timed out after <*>ms. x144 new template, distance 0.678 > 0.393
NOVEL_TEMPLATE WARN PaymentService Payment gateway timeout after <*> ms for order <*>, retry <*> of <*> x90 new template, distance 0.459 > 0.393
NOVEL_TEMPLATE ERROR OrderController Failed to process order <*>: Unable to acquire JDBC Connection x108 new template, distance 0.434 > 0.393
NOVEL_TEMPLATE INFO OrderController Order <*> placed by customer c-<*> total=<*> currency=INR x156 new template, distance 0.394 > 0.393
RATE_SPIKE WARN PaymentService Payment declined for order <*>: insufficient funds x44 peak 44 per 5 min vs baseline mean 2.6 (std 0.9), z = 45.6
Three real findings (the pool timeout, the JDBC failure, the gateway timeout), one real surge (declined payments: 44 in five minutes against a baseline mean of 2.6), and one false alarm (the reworded order line). Findings are sorted by kind, then score, because the two scores are different units: a cosine distance is below 1 and a z-score here is 45.6. Sorting them together would put every surge above every new template for no good reason.
Going deeper: why two detectors and not one
A rate detector alone cannot see a new kind of message that appears 90 times in one bucket in a baseline where it never existed, because there is no baseline rate to compare with (the module deliberately skips templates the baseline has not seen, so the two detectors do not double-report). A novel-template detector alone cannot see a familiar template that suddenly fires many times as often. The 44 declined payments are exactly that case: the template is in the baseline, its distance is whatever it always was, and only the count gives it away.The cost of the rate detector is its window. Five-minute buckets mean a spike is reported up to five minutes late, and a baseline of two hours gives a standard deviation estimated from 24 buckets, which is few. A week of baseline per hour-of-day would be sturdier, and would make rare templates such as the cache refresh (twice in two hours) less noisy to judge.
What it does not see
This is the section that decides whether you should trust the tool, so it uses the same run, not a new one. Two things are wrong in the target window and are not flagged, and one thing is flagged that is not wrong. From output/05-detection.txt:pool stats template known to the baseline: true
during the incident: HikariPool-1 - Pool stats (total=10, active=10, idle=0, waiting=32)
during normal times: HikariPool-1 - Pool stats (total=10, active=2, idle=8, waiting=0)
'but ledger write failed' has distance 0.256, threshold 0.393, so it is NOT flagged
## Flagged, although nothing is wrong
the deployment's reworded order line has distance 0.394 against threshold 0.393
Blind spot one: numbers. The pool statistics line is the best evidence in the whole log. During the incident it says active=10, idle=0, waiting=32; during normal times active=2, idle=8, waiting=0. After masking both are the same template, and a template that is already known with a normal rate is invisible to both detectors. Anything that is a value rather than a kind of message belongs in a metric (hikaricp.connections.pending is exactly this number), not in a log detector.
Blind spot two: look-alikes. “Payment approved … but ledger write failed” is a serious bug, and it scores 0.256, inside the threshold, because it shares nearly every word with a message that is normal. I would not expect a model to rescue this by itself: the two sentences are close in meaning and in wording, and the difference is one clause.
The false alarm. The deployment’s reworded order line scores 0.394 against a threshold of 0.393, which is a flag by a margin of 0.001. That is not the detector understanding anything; it is where I put the margin. The sweep shows how thin it is, from output/06-threshold-sweep.txt:
worst baseline distance: 0.343
margin 0.00 -> threshold 0.343 -> 4 of 5 new templates flagged: Order <*> | HikariPool-<*> - | Failed to | Payment gateway
margin 0.05 -> threshold 0.393 -> 4 of 5 new templates flagged: Order <*> | HikariPool-<*> - | Failed to | Payment gateway
margin 0.10 -> threshold 0.443 -> 2 of 5 new templates flagged: HikariPool-<*> - | Payment gateway
margin 0.20 -> threshold 0.543 -> 1 of 5 new templates flagged: HikariPool-<*> -
At margin 0.10 the harmless reword disappears, and so does the JDBC error, an ERROR that mattered. No single margin separates the three real findings from the reword unless it sits between 0.394 and 0.434, which I could only know after seeing the answer. The order is better than the cut-off, also in output/06-threshold-sweep.txt:
the three real new templates score 0.678, 0.434, 0.459
the harmless reword scores 0.394, so it ranks below all three
a threshold between 0.394 and 0.434 would split them, but it is chosen after seeing the answer
Use the ranking, not the cut-off. In this run the three real new templates (0.678, 0.434, 0.459) all outrank the harmless reword (0.394), so a list sorted by distance puts the right things first. Turning that list into a pager rule needs more than a threshold. Two cheap additions that this module does not implement and I have not measured: always flag a new ERROR template regardless of distance, and never page on a new INFO template. Both are one-line rules and both would change the numbers above.
Going deeper: what would actually close these gaps
Numbers. Extract the values you care about (pool waiting count, latency in milliseconds) into metrics and alert on those; a log detector is the wrong tool and Micrometer is the right one. The OpenTelemetry and Micrometer comparison covers getting them out of a Spring Boot application.Look-alikes. A level change inside the same template is a cheap signal:
ERROR appearing in a template that was always INFO would show in the template key, because the level is part of it. A message that is merely longer than its sibling is not something a bag of words can tell you about.The margin. Calibrate it against a labelled history of your own incidents, not against a single run. What I can say from this one is that the ordering was right and the cut-off was fragile, on synthetic data built to contain exactly these cases, so treat any real-world accuracy figure you read about this approach (including by implication this article) with suspicion until it is measured on your logs.
From findings to one page, and one summary
Five findings in ten minutes are one incident, not five pages. IncidentBuilder.java joins findings whose time spans are within ten minutes of each other, which here gives one incident of 542 events with ERROR severity. Note what that includes: the reword that started at minute 5 pulls the incident’s start time five minutes before the real problem began, a small, honest cost of the false alarm. From output/07-incident.txt:5 findings -> 1 incident(s)
window 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30, 5 findings, 542 events
The no-model summary is the default and it never invents anything: it counts, names the window and quotes the top templates (TemplateSummarizer.java). A model is useful for the one thing counting cannot do, which is turning five templates into “the pool ran out of connections, probably after the payment gateway slowed”. The module’s prompt is built from the templates only (IncidentSummarizer.java):
You are helping an on-call engineer. Below are the anomalous log templates from one incident.
Write 3 sentences: what changed, the likely cause, and what to check first.
Only use facts from the list; do not invent hosts, versions or numbers.
Window: 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30
1. [ERROR] HikariPool: HikariPool-<*> - Connection is not available, request timed out after <*>ms. (NOVEL_TEMPLATE, 144 events, new template, distance 0.678 > 0.393)
2. [WARN] PaymentService: Payment gateway timeout after <*> ms for order <*>, retry <*> of <*> (NOVEL_TEMPLATE, 90 events, new template, distance 0.459 > 0.393)
3. [ERROR] OrderController: Failed to process order <*>: Unable to acquire JDBC Connection (NOVEL_TEMPLATE, 108 events, new template, distance 0.434 > 0.393)
4. [INFO] OrderController: Order <*> placed by customer c-<*> total=<*> currency=INR (NOVEL_TEMPLATE, 156 events, new template, distance 0.394 > 0.393)
5. [WARN] PaymentService: Payment declined for order <*>: insufficient funds (RATE_SPIKE, 44 events, peak 44 per 5 min vs baseline mean 2.6 (std 0.9), z = 45.6)
Here is why that matters. The raw window is 2,196 lines and 310,589 characters. The prompt is 1,112 characters (the end of output/07-incident.txt):
raw target window: 2196 physical lines, 310589 characters
prompt: 1112 characters (0.4% of the raw window)
0.4% of the raw window is the difference between a prompt you can afford on every incident and one you cannot, and the stack trace never leaves your machine (the test asserts that the prompt contains no exception class name and no stack-trace line). It also limits what the model can say wrong: it has five sentences to work from and the instruction not to invent anything beyond them. That instruction is not a guarantee, and the module has no guard that checks the reply, unlike the release-notes module in the same repository.
Going deeper: the chat-endpoint summariser, and what was not tested
LlmSummarizer posts the prompt to any POST /v1/chat/completions endpoint with temperature 0 and returns the reply text. The test starts a stub server and asserts the request shape and that the reply is parsed; the transcript is below. It has never been run against a real model. I can tell you what the request looks like and that nothing the stub receives contains a stack trace, and I cannot tell you whether a real model’s three sentences are any good, or how often one of them would assert something the five templates do not support.request model: stub-model, temperature: 0, messages: 1
request content characters: 1112
contains a stack-trace line: false
reply: STUB REPLY: the pool ran out of connections.
Not run against a real model. The stub proves the request shape and the reply parsing.If you wire this to a paid model, add a guard that checks the reply only names templates, counts and loggers that appear in the incident, as the release-notes module does for PR numbers and commit hashes. Without it, a confident wrong sentence at 2 a.m. is worse than no sentence.
Serving it from Spring Boot
The Spring Boot part is deliberately small: a service that reads two files, fits the model on the first and reports incidents in the second, and one controller. The service is the pipeline in five lines (AnalysisService.java): TemplateMiner miner = new TemplateMiner(false, 0);
BaselineModel model = new BaselineModel(embedder, miner.mine(base.events()), k);
double threshold = model.worstBaselineDistance() + margin;
AnomalyDetector detector = new AnomalyDetector(model, miner, base.events(), threshold, Duration.ofMinutes(5), 4.0, 15);
List<Incident> incidents = new IncidentBuilder(Duration.ofMinutes(10)).build(detector.detect(target.events()));
A @SpringBootTest starts the application on a random port and calls it over HTTP (EndpointTest.java); the packaged jar answers curl the same way. From output/13-jar-curl.txt:
$ curl -s "localhost:18080/api/incidents?baseline=target/sample-logs/baseline.log&target=target/sample-logs/target.log"
{
"baselineLines": 3947,
"targetLines": 2196,
"baselineTemplates": 10,
"targetTemplates": 14,
"clusters": 4
}
ERROR incident from 2026-11-30 11:05:13 +05:30 to 2026-11-30 11:29:46 +05:30: 4 new message kinds and 1 known messages surging, 542 events in all. Top: "HikariPool-<*> - Connection is not available, request timed out after <*>ms." (HikariPool, 144x); "Payment gateway timeout after <*> ms for order <*>, retry <*> of <*>" (PaymentService, 90x); "Failed to process order <*>: Unable to acquire JDBC Connection" (OrderController, 108x).
Do not deploy this endpoint. It takes file paths as request parameters and reads them on the server, so anyone who can call it can ask it to read any file the process can read, and a missing file is an unhandled exception (the last line of that transcript file is an HTTP 500 for a path that does not exist). It is a demonstration of the pipeline over HTTP, nothing more. A real version reads from your log store, not from a path the caller chooses.The endpoint also re-fits the model on every call, which is fine for ten templates and wrong for ten thousand. In a real service you would fit once per baseline window, keep the
BaselineModel as a bean, and only run the detector on new data.
Going deeper: running it on your own logs
Write two log files with the same layout, a baseline of normal traffic and a target window you want checked, then callGET /api/incidents?baseline=...&target=.... SampleLogWriter writes the synthetic pair used here. Things to change first: the cluster count (logs.clusters), the margin (logs.margin), and the regular expression in LogParser if your layout is not the default. Things to check first: that the baseline contains a normal amount of WARN and ERROR, and that the orphan-line count in the parse step is zero.
Should you build this?
Probably not yet, and here is the order I would try things in. (1) Alert on metrics you already have: error rate, latency, pool pending, consumer lag. They catch the numbers-only failure that this article shows a log detector cannot. (2) Add a plain “new ERROR template appeared” alert; it is a set lookup and needs no model. (3) Only then add embeddings, and only to rank new templates so a reworded INFO line does not wake anyone.
What this pipeline gives you in return for the complexity is a ranking of new kinds of message and an incident summary that is a fraction of a percent of the raw log. What it does not give you is a threshold you can trust without your own labelled incidents, or any understanding of whether a message is bad. Everything above was measured on synthetic logs that I built to contain these cases; on real logs the first thing you are likely to meet is the template-explosion problem, not the clustering.
Further reading
- The companion module: asmhatre/java-ai-agents/log-anomaly, with every transcript in output/
- Related on this blog: a swappable embedder behind a code-search server, measuring retrieval quality with a golden dataset, OpenTelemetry vs Micrometer in Spring Boot 4, running Java like a script
- Spring Boot reference: logging
- scikit-learn: k-means
No Comments yet!