IntermediateGeneralPOC to production
I rewrote my Python log parser in Rust. Was it worth it?
AI engineering is learning by doing, and sometimes the doing is a rewrite you suspect you don't need. My hybrid log watcher's regex counters were written in Python. I ported them to Rust, checked that every counter matched, and measured both on my DGX Spark: parsing alone got 14x to 39x faster. Whether that mattered depended entirely on the traffic, and the cheapest win didn't need Rust at all.
- Time
- About 30 minutes
- Checked
If a button name on the screen does not match this guide, follow the action. These products rename buttons often.
Steps
The question
In the hybrid log watching recipe, Python regex counters read every line of a busy SIP proxy log, and a model on my DGX Spark only looked when a counter tripped. It worked. But it raised the question every AI engineer runs into on the way to production: should the hot path be in Rust?
The languages guide says to measure before you rewrite. So I did both: I measured, then rewrote anyway to see what the rewrite actually buys. This guide walks through the same steps with code you can run on a small synthetic log.
Build a test you can repeat
Never benchmark on a real production log you can't share or replay. I used a synthetic SIP-proxy-style debug log: made-up lines in the same shape as the real thing. The benchmark log had 5 million lines (421 MB), tuned to about 324 lines per second of timestamps with about 0.45% of lines containing the word "error," like the real stream.
This smaller generator makes the same kind of log. Save it as
gen_log.pyand runpython3 gen_log.py 200000:"""Write a synthetic SIP-proxy-style debug log. No real hosts, numbers, or users.""" import random import sys from datetime import datetime, timedelta lines = int(sys.argv[1]) if len(sys.argv) > 1 else 200_000 rate = 324 # lines per second, like the real stream random.seed(42) t = datetime(2026, 10, 18, 10, 0, 0) step = timedelta(seconds=1 / rate) burst_left = 0 with open("synthetic.log", "w", encoding="utf-8") as out: for i in range(lines): ts = t.strftime("%Y-%m-%d %H:%M:%S.") + f"{t.microsecond // 1000:03d}" cid = f"{random.getrandbits(32):08x}" if burst_left == 0 and random.random() < 0.00004: burst_left = random.randint(3, 8) # a short burst of real errors r = random.random() if burst_left and random.random() < 0.05: burst_left -= 1 msg = f"app-error- tm: transaction timeout call-id={cid}" elif r < 0.0044: # debug noise that says "error" msg = random.choice([ f"app-debug- tm: no error route set, using default call-id={cid}", f"app-debug- sl: reply sent, error_count=0 call-id={cid}", f"app-debug- core: ErrorLog level is 3", ]) elif r < 0.0054: # named errors and warnings, header dumps msg = random.choice([ f"app-error- HttpClient[7f3a1c40aa00]: upstream request timed out call-id={cid}", f"app-error- sres(q=svc.example.invalid): [7f3a1c40b540] no answer call-id={cid}", f"app-warning- SipEvent[7f3a1c40c100]: subscriber gone call-id={cid}", f"app-warning- Registrar 0x{random.getrandbits(48):012x}: binding expired call-id={cid}", f"app-warning- dns module: cache miss for svc.example.invalid call-id={cid}", f"app-debug- Via: SIP/2.0/UDP proxy.example.invalid;branch=z9hG4bK{cid}", f"app-debug- retrying the request in 2 seconds call-id={cid}", ]) elif r < 0.30: msg = f"app-debug- sip: INVITE sip:user{random.randint(1, 999)}@example.invalid call-id={cid}" elif r < 0.31: msg = f"app-debug- sip: SIP/2.0 503 Service Unavailable call-id={cid}" elif r < 0.33: msg = f"app-debug- sip: SIP/2.0 486 Busy Here call-id={cid}" elif r < 0.60: msg = f"app-debug- sip: SIP/2.0 200 OK call-id={cid}" elif r < 0.75: msg = f"app-debug- core: processing message len={random.randint(300, 1400)} call-id={cid}" else: # lines that carry a component msg = random.choice([ f"app-debug- core: [{random.getrandbits(48):012x}] message parsed call-id={cid}", f"app-debug- tm: [tm-worker] retransmit timer set call-id={cid}", f"app-debug- auth: AuthModule checked credentials call-id={cid}", f"app-debug- dlg: DialogManager updated state call-id={cid}", f"app-debug- core: ModuleRouter picked a route call-id={cid}", f"app-debug- ua: [ua-café] display name updated call-id={cid}", ]) out.write(f"{ts} {msg}\n") t += stepEach line looks like
2026-10-18 10:00:00.006 app-debug- sip: SIP/2.0 200 OK call-id=e465e150. About a quarter of the lines carry a component: a bracketed tag like[tm-worker]or a word likeDialogManager. A small share are named errors and warnings likeHttpClient[7f3a1c40aa00]: upstream request timed out. Those matter in the last two experiments. The fixed seed means you get the same file every time, so runs are comparable.Start from the Python counters
These are the counters, in the same style as the recipe: several compiled regexes checked against every line, plus a trip whenever one second has 3 or more errors. A trip is what wakes the model. Save as
counters.py:"""Count patterns in a log with regexes, one line at a time (the original design).""" import re import sys from collections import Counter ERROR_ANY = re.compile(r"error", re.IGNORECASE) # any "error" keyword ERROR_LEVEL = re.compile(r"^\S+ \S+ app-(?:error|fatal|critical)- ") # the log-level token only TIMEOUT = re.compile(r"transaction timeout") REPLY_5XX = re.compile(r"SIP/2\.0 5\d\d ") INVITE = re.compile(r" INVITE sip:") STATUS = re.compile(r"SIP/2\.0 (\d{3}) ") TRIP_AT = 3 # errors in one second that should wake the model def count(path: str, error_re: re.Pattern) -> dict: c = Counter() status = Counter() errors_per_second = Counter() with open(path, encoding="utf-8") as f: for line in f: c["lines"] += 1 if error_re.search(line): c["errors"] += 1 errors_per_second[line[:19]] += 1 # "YYYY-MM-DD HH:MM:SS" if TIMEOUT.search(line): c["timeouts"] += 1 if REPLY_5XX.search(line): c["replies_5xx"] += 1 if INVITE.search(line): c["invites"] += 1 for code in STATUS.findall(line): status[code] += 1 trips = sorted(sec for sec, n in errors_per_second.items() if n >= TRIP_AT) return {"counts": c, "status": status, "trips": trips} if __name__ == "__main__": path = sys.argv[1] error_re = ERROR_LEVEL if "--level" in sys.argv else ERROR_ANY r = count(path, error_re) for k in ("lines", "errors", "timeouts", "replies_5xx", "invites"): print(f"{k}={r['counts'][k]}") for code in sorted(r["status"]): print(f"status_{code}={r['status'][code]}") print(f"trips={len(r['trips'])}") for sec in r["trips"]: print(f"trip {sec}")Run
python3 counters.py synthetic.log > py.txt. That output file is your reference: anything faster has to produce exactly the same text.Profile first
A profiler shows where the time goes, so you rewrite the right thing. Two easy ones:
python3 -m cProfile -o counters.prof counters.py synthetic.log > /dev/null python3 -c "import pstats; pstats.Stats('counters.prof').sort_stats('tottime').print_stats(8)" uvx py-spy record -o profile.svg -- python3 counters.py synthetic.logcProfileships with Python. The first command saves a profile (the script's own output goes to/dev/null), and the second prints the top 8 functions bytottime, the time spent inside each function itself.py-spysamples the running program and writes a flame graph, an SVG you open in a browser where wider bars mean more time.uvxruns py-spy without installing it;pip install py-spyworks too.On the Spark, the 5M-line run broke down like this:
- about 56% in
re.search, because there are 4 regexes per line - about 21% in interpreter bookkeeping: the loop, the counters, and the dictionary updates
- about 7% in
findall - error normalization (cleaning up error text before grouping) was negligible
So it's the regexes and the per-line Python overhead, not anything clever. That points to two fixes: run fewer or tighter regexes, or run the same regexes somewhere with no per-line interpreter cost.
- about 56% in
Try the cheap fix: a tighter regex
The original error counter matches any "error," so debug lines like
no error route setcount as errors. Match the log-level token instead:ERROR_ANY = re.compile(r"error", re.IGNORECASE) # before ERROR_LEVEL = re.compile(r"^\S+ \S+ app-(?:error|fatal|critical)- ") # afterRun
python3 counters.py synthetic.log --leveland compareerrors=andtrips=with the first run.On the benchmark log, this one change:
- cut error matches by 97.5%
- cut model-triggering trips by 97%
- made the Python parser 26% faster
The tighter pattern is also cheap on its own: in a per-regex timing, the level-token match took 106 ns per line in Python, under an eighth of the keyword error regex, with about 97% fewer false positives.
Adjust the pattern to your own log format. The win is the same idea either way: count severities, not words. It costs one line of code and no new language.
Port the counters to Rust
Now the experiment. The Rust version uses the same regexes through the regex crate, reads the file through a memory map (memmap2), and has an optional multi-core mode using rayon. A memory map lets the program read the file as if it were already in memory, and the operating system loads pages as needed. rayon spreads work across CPU cores with almost no extra code.
cargo new logcount-rs && cd logcount-rs cargo add regex@1 rayon@1 memmap2@0.9Replace
src/main.rswith://! Count patterns in a log with the same regexes as counters.py. //! Usage: logcount-rs <file> [--level] [--parallel] use std::collections::BTreeMap; use std::{env, fs::File}; use memmap2::Mmap; use rayon::prelude::*; use regex::bytes::Regex; const TRIP_AT: u64 = 3; // errors in one second that should wake the model #[derive(Clone)] struct Patterns { error: Regex, timeout: Regex, reply_5xx: Regex, invite: Regex, status: Regex, } #[derive(Default)] struct Counts { lines: u64, errors: u64, timeouts: u64, replies_5xx: u64, invites: u64, status: BTreeMap<Vec<u8>, u64>, errors_per_second: BTreeMap<Vec<u8>, u64>, } impl Counts { fn merge(mut self, other: Counts) -> Counts { self.lines += other.lines; self.errors += other.errors; self.timeouts += other.timeouts; self.replies_5xx += other.replies_5xx; self.invites += other.invites; for (k, v) in other.status { *self.status.entry(k).or_default() += v; } for (k, v) in other.errors_per_second { *self.errors_per_second.entry(k).or_default() += v; } self } } fn count_chunk(p: &Patterns, data: &[u8]) -> Counts { let mut c = Counts::default(); for line in data.split(|&b| b == b'\n').filter(|l| !l.is_empty()) { c.lines += 1; if p.error.is_match(line) { c.errors += 1; let second = &line[..line.len().min(19)]; // "YYYY-MM-DD HH:MM:SS" *c.errors_per_second.entry(second.to_vec()).or_default() += 1; } if p.timeout.is_match(line) { c.timeouts += 1; } if p.reply_5xx.is_match(line) { c.replies_5xx += 1; } if p.invite.is_match(line) { c.invites += 1; } for caps in p.status.captures_iter(line) { *c.status.entry(caps[1].to_vec()).or_default() += 1; } } c } /// Split `data` into about `n` pieces that each end on a newline. fn line_chunks(data: &[u8], n: usize) -> Vec<(usize, usize)> { let size = (data.len() / n.max(1)).max(1); let mut chunks = Vec::new(); let mut start = 0; while start < data.len() { let mut end = (start + size).min(data.len()); while end < data.len() && data[end - 1] != b'\n' { end += 1; } chunks.push((start, end)); start = end; } chunks } fn main() -> Result<(), Box<dyn std::error::Error>> { let args: Vec<String> = env::args().collect(); let path = args.get(1).ok_or("usage: logcount-rs <file> [--level] [--parallel]")?; let level = args.iter().any(|a| a == "--level"); let parallel = args.iter().any(|a| a == "--parallel"); let error = if level { Regex::new(r"^\S+ \S+ app-(?:error|fatal|critical)- ")? // the log-level token only } else { Regex::new(r"(?i)error")? // any "error" keyword, like the original }; let p = Patterns { error, timeout: Regex::new(r"transaction timeout")?, reply_5xx: Regex::new(r"SIP/2\.0 5\d\d ")?, invite: Regex::new(r" INVITE sip:")?, status: Regex::new(r"SIP/2\.0 (\d{3}) ")?, }; let file = File::open(path)?; // Safety: the file must not be truncated while we read it. let data = unsafe { Mmap::map(&file)? }; let c = if parallel { let chunks = line_chunks(&data, rayon::current_num_threads() * 4); chunks .par_iter() .map_init(|| p.clone(), |p, &(a, b)| count_chunk(p, &data[a..b])) // one clone per thread .reduce(Counts::default, Counts::merge) } else { count_chunk(&p, &data) }; println!("lines={}", c.lines); println!("errors={}", c.errors); println!("timeouts={}", c.timeouts); println!("replies_5xx={}", c.replies_5xx); println!("invites={}", c.invites); for (code, n) in &c.status { println!("status_{}={}", String::from_utf8_lossy(code), n); } let trips: Vec<_> = c.errors_per_second.iter().filter(|(_, n)| **n >= TRIP_AT).collect(); println!("trips={}", trips.len()); for (second, _) in trips { println!("trip {}", String::from_utf8_lossy(second)); } Ok(()) }Three details matter:
regex::bytes::Regexsearches raw bytes from the memory map, so no line is copied or decoded first. The patterns are the same as in Python.map_init(|| p.clone(), ...)gives each worker thread its own copy of the regexes. The regex docs warn that sharing one regex across threads can cause contention on its internal scratch-space pool. A clone shares the compiled program, so it costs almost nothing.- Chunks end on newlines, and per-second counts are merged after the parallel pass, so a trip that spans two chunks is still counted correctly.
Prove it counts the same
A faster parser that counts differently is a bug, not a win. Build it and compare every line of output against the Python reference:
cargo build --release cd .. && R=logcount-rs/target/release/logcount-rs python3 counters.py synthetic.log > py.txt $R synthetic.log > rs.txt && diff py.txt rs.txt && echo "1 thread: match" $R synthetic.log --parallel > rs_par.txt && diff py.txt rs_par.txt && echo "parallel: match" python3 counters.py synthetic.log --level > py_level.txt $R synthetic.log --level --parallel > rs_level.txt && diff py_level.txt rs_level.txt && echo "level: match"diffprints nothing when the files are identical. In the benchmark, every counter matched exactly, including the order of trips. Time each command withtimeon your own machine. Your numbers will differ from mine, so compare them with each other, not with the table below.The results
Parsing only, on the 5M-line log (Python running the original regex counters unchanged):
Run Time Lines per second Memory (RSS) Speedup Python 27.3 s 183k 14 MB 1x Rust, 1 thread 1.97 s 2.54M 6 MB 13.8x Rust, best multi-core run 0.70 s 7.1M not measured about 39x RSS (resident set size) is how much memory the process actually used. The multi-core run didn't scale perfectly with core count. The Spark's CPU is big.LITTLE, a mix of fast and efficient cores, and moving work between the two core clusters has a cost.
End to end as a replay (reading the whole file as fast as possible), with a vision model called every 10 seconds and on every counter trip:
Measure Python design Rust parser Change Total run time 30.7 s 2.9 s 10.5x faster Time to flag an error burst 1.76 s 0.29 s about 6x faster During a burst model thread starved for about 27 s no starvation fixed That last row was the real surprise. In the Python design, the parser and the model-calling thread shared a lock and Python's GIL (global interpreter lock, which lets only one thread run Python code at a time). Under a burst, the parser held on so tightly that the model thread waited about 27 seconds to send its call. With the parser in Rust, the Python side has almost nothing to do, and the model gets called on time.
The paced runs: real rate and a burst
A replay shows the ceiling, but a live watcher reads lines as they arrive. So the final test paced the synthetic SIP-proxy-style log: lines fed at a fixed rate, with the vision model called every 10 seconds and on each counter trip. One run held the normal rate, and one simulated an incident.
Measure Steady ~324 lines/s, 180 s: Python Steady: Rust Burst ~34k lines/s, 60 s: Python Burst: Rust Kept up with the log yes, no lag yes, no lag yes, no lag yes, no lag Pipeline CPU (share of one core) 1.3% 0.9% 43.6% 4.0% Model calls 21 22 20 28 Mean model latency 2.30 s 1.90 s 2.77 s 1.99 s Time to flag 3.15 s 2.44 s about 0.1–0.15 s about 0.1–0.15 s - At the steady rate, both parsers kept up, and the differences are small: slightly less CPU and slightly faster flags with Rust.
- During the burst, both still kept up, but Python needed 43.6% of a core against Rust's 4.0%, about 10x less. The model side felt it too: Python got 20 model calls through at 2.77 s each, and Rust got 28 at 1.99 s. The Python parser thread competes with the model-call thread for the GIL, so every call waits a little longer.
Where the Python time goes, per regex. The benchmark's counters, timed one regex at a time in nanoseconds (ns, billionths of a second) per line:
Counter regex Python (ns/line) Rust (ns/line) Rust speedup Component tag 1,630 (30% of the total) 191 about 8x Fatal 963 21 about 46x Error 884 23 about 38x Warning 776 19 about 41x Method 609 38 about 16x Response 287 34 about 8x Full pass, all counters about 5,450 (184k lines/s) about 445 (whole CLI) about 12x Rust is 8 to 46 times faster per regex and about 12 times faster overall. The slowest regex is the same in both languages: the broad component tag pattern.
So, was it worth it?
At the normal rate, Rust buys lower CPU, not speed. At a steady ~324 lines per second, both parsers kept up with no lag. Python parsing uses about 0.2% of one CPU core, the whole pipeline about 1.3% (0.9% with Rust), and the model is about 98% of pipeline time. Nothing you'd notice gets faster.
During bursts, Rust earns its place. At ~34k lines per second, Rust used about 10x less CPU (4.0% against 43.6% of a core) and kept model calls flowing: 28 calls against 20, each one faster. Rust also helps with:
- Backlogs: the watcher restarts and has to catch up on an hour of lines. The replay results show how fast that catch-up can be.
- Fan-in: one watcher reads many servers' logs at once, so a burst on any of them adds up.
- GIL and lock contention: a busy Python parser slows the model thread, and in the unpaced replay it starved it for about 27 seconds. With the parser in Rust, the problem goes away instead of needing to be tuned around.
And either way, tighten the regex first. It was the cheapest win: one line of code that cut model trips by 97% in both languages. It made Python 26% faster, while Rust stayed about the same.
Next cheap fix: the component regex
The per-regex table points at the next win, and it isn't a new language. The broad component tag regex is the hot spot in both languages. It finds a bracketed tag or a word ending in Module, Agent, or Manager:
COMP = re.compile(r"\[(\w[\w-]*)\]|\b(\w+(?:Module|Agent|Manager))\b")Python has to scan the whole line looking for either branch. Tested on the 5M-line synthetic log, pinned to one fast core, it cost 1,469 ns per line in Python and 188 ns in Rust.
The shortcut that lied. The first idea was to stop searching and read the tag from where it "always" sits: the anchored
^\S+ \S+ (\S+), or just the third space-separated field. Those ran at 128–192 ns per line, a big speedup, and they were wrong on 83–90% of lines. The tag isn't at a fixed field, and the third field is actually the log-level token. A fast answer that's wrong is worse than a slow one. Check that a shortcut gives the same result before you trust its speed.The fix that's exact by construction. The regex can only match if the line contains
[or one of the three suffix words. So check for those with plain substring tests first, which are much cheaper than a regex:- None of them: skip the regex. The answer is "no component."
- Only
[: use a smaller bracket-only regex. - A suffix word: use the original regex.
Pure-ASCII lines also get regexes compiled with
re.ASCII, which is faster. Lines with any non-ASCII character fall back to the Unicode versions, so\wstill matches letters like é. Save this ascomponent.py:"""Find each line's component tag two ways and prove they agree.""" import re import sys import time from collections import Counter # The original: a bracketed tag like [tm-worker], or a word ending in Module/Agent/Manager. COMP = re.compile(r"\[(\w[\w-]*)\]|\b(\w+(?:Module|Agent|Manager))\b") COMP_ASCII = re.compile(COMP.pattern, re.ASCII) # Bracket-only version, for lines with "[" but none of the suffix words. BR = re.compile(r"\[(\w[\w-]*)\]") BR_ASCII = re.compile(BR.pattern, re.ASCII) # A tempting shortcut: "the tag is the 3rd space-separated field." It isn't. SHORTCUT = re.compile(r"^\S+ \S+ (\S+)") def comp_shortcut(line: str) -> str: m = SHORTCUT.search(line) return m.group(1) if m else "?" def comp_original(line: str) -> str: m = COMP.search(line) return (m.group(1) or m.group(2)) if m else "?" def comp_fast(line: str) -> str: """Same answer as comp_original, but skips the regex when it can't match.""" ascii_only = line.isascii() # ASCII regexes are safe (and faster) on pure-ASCII lines if "Module" in line or "Agent" in line or "Manager" in line: m = (COMP_ASCII if ascii_only else COMP).search(line) return (m.group(1) or m.group(2)) if m else "?" if "[" not in line: return "?" # neither branch of the original regex can match m = (BR_ASCII if ascii_only else BR).search(line) return m.group(1) if m else "?" if __name__ == "__main__": with open(sys.argv[1], encoding="utf-8") as f: lines = f.readlines() for name, fn in (("original", comp_original), ("fast", comp_fast)): start = time.perf_counter() tags = Counter(fn(line) for line in lines) ns = (time.perf_counter() - start) / len(lines) * 1e9 print(f"{name}: {ns:.0f} ns/line, {sum(n for t, n in tags.items() if t != '?')} lines tagged") mismatches = sum(comp_original(line) != comp_fast(line) for line in lines) print("fast vs original, mismatches:", mismatches) wrong = sum(comp_original(line) != comp_shortcut(line) for line in lines) print(f"shortcut vs original, wrong on {wrong / len(lines):.0%} of lines")Run
python3 component.py synthetic.log. It times both versions, counts the lines wherecomp_fastdisagrees withcomp_original(it should print 0), and shows how often the third-field shortcut is wrong. Also run it on a small file of tricky lines you write yourself: both a tag and a suffix word,ModuleRouter, empty brackets, and non-ASCII tags.In the benchmark:
Measure Before After Change Python, component regex 1,469 ns/line 304 ns/line 4.8x faster Python, full pass 182k lines/s 237k lines/s +30% Rust, component regex 188 ns/line 85 ns/line 2.2x faster Rust, full single-thread pass 2.60M lines/s 3.55M lines/s +36% - In Python, the pre-check alone brought it to 704 ns per line and the ASCII flag alone to 1,020. Together they reached 304.
- In Rust, the gain came from using
find()and slicing instead of capture groups. The ASCII flag made no difference in Rust. - The tag matched the original on every line, and the counter output was identical on the 5M-line log, a 200k-line sample, and an edge-case file.
Caveats. The gain depends on how many lines contain
[or a suffix word: 45% in the benchmark log. "Module" also appears inside words like "ModuleRouter," which pass the pre-check but don't match. Real logs may have more bracketed lines, so your gain could be smaller. And in the original log, the "component" is mostly a hex object pointer. A layout-aware extractor that reads the real component field would be more useful, but it would change what the counter means, so it's a separate decision, not a speedup. The next step makes that decision.The lesson matches the rest of this guide: the cheapest wins came from doing less work, and they helped in both languages.
From pointers to names: extract what's actually failing
Speeding up the component regex left a bigger problem. In the original log, the "component" was mostly a hex object pointer, like
0x…a00. That's opaque to me, and to the model that gets the counts. So I changed what "component" means: instead of the first tag anywhere in the line, extract the readable name of the thing that logged it. This changes what the counter reports, so it was a deliberate decision, not a refactor.The rule:
- Only lines in the
<date> <time> app-<level>- <msg>layout count. Anything else gets?. - If the message starts with
Name[,Name(,Name:,Name::method, orName 0x, the name is that leading identifier. - Otherwise, only if a cheap substring pre-check finds
[or a suffix word, take the first non-hex[Name]or the first word ending in Module, Agent, or Manager. - Otherwise,
?.
Both languages use ASCII character classes. Save this as
names.py, next tocomponent.py:"""Turn each line's opaque component into a readable name, and compare the two.""" import re import sys import time from collections import Counter from component import comp_original # the old answer: often a hex pointer # A leading identifier followed by "[", "(", ":", "::method", or " 0x". HEAD = re.compile(r"([A-Za-z_]\w*)(?:::\w+)*(?:\[|\(|:| 0x)", re.ASCII) # Otherwise: the first non-hex [Name], or a word ending in Module/Agent/Manager. ANY = re.compile(r"\[([A-Za-z_][\w-]*)\]|\b(\w+(?:Module|Agent|Manager))\b", re.ASCII) def name(line: str) -> str: parts = line.split(" ", 3) # date, time, level, message if len(parts) < 4: return "?" level, msg = parts[2], parts[3] if not (level.startswith("app-") and level.endswith("-")): return "?" # not the "<date> <time> app-<level>- <msg>" layout m = HEAD.match(msg) if m: return m.group(1) # Cheap substring pre-check before the slower search. if "[" in msg or "Module" in msg or "Agent" in msg or "Manager" in msg: m = ANY.search(msg) if m: return m.group(1) or m.group(2) return "?" CASES = [ # (message after "2026-10-18 10:00:00.000 ", expected name) ("app-error- HttpClient[7f3a00c1a00]: timed out", "HttpClient"), ("app-error- sres(q=svc.example.invalid): no answer", "sres"), ("app-debug- Router::pick::retry: no route", "Router"), ("app-warning- SipEvent(0x7f3a): gone", "SipEvent"), ("app-warning- Registrar 0x7f3a: expired", "Registrar"), ("app-debug- core: [abc] parsed", "core"), ("app-debug- parsed [7f3a00c1] then [tm-worker]", "tm-worker"), # skips the hex tag ("app-debug- the AuthModule said no", "AuthModule"), ("app-debug- ModuleRouter picked a route", "?"), # passes the pre-check, no match ("app-warning- dns module: cache miss", "?"), # the lowercase "module:" form ("app-debug- Via: SIP/2.0/UDP proxy", "?"), # header dump ("app-debug- [ua-café] updated", "?"), # ASCII classes stop at é ("not the app layout at all", "?"), ] if __name__ == "__main__": for msg, want in CASES: got = name("2026-10-18 10:00:00.000 " + msg) assert got == want, f"{msg!r}: got {got!r}, want {want!r}" print(f"edge cases: {len(CASES)} passed") with open(sys.argv[1], encoding="utf-8") as f: lines = f.readlines() start = time.perf_counter() names = [name(line) for line in lines] ns = (time.perf_counter() - start) / len(lines) * 1e9 print(f"name(): {ns:.0f} ns/line, '?' on {names.count('?') / len(lines):.0%} of lines") for level in ("app-error-", "app-warning-"): old, new = Counter(), Counter() for line, n in zip(lines, names): if line.split(" ", 3)[2:3] == [level]: old[comp_original(line)] += 1 new[n] += 1 print(f"\n{level} top sources") print(" before:", ", ".join(f"{k} {v}" for k, v in old.most_common(3))) print(" after: ", ", ".join(f"{k} {v}" for k, v in new.most_common(3)))Run
python3 names.py synthetic.log. It checks the edge cases first, then prints the share of?lines and the top error and warning sources before (the old component) and after (the name). Your timing will differ from mine, so use it only to compare runs on your own machine.On the generator in this guide, almost every message starts with a subsystem prefix like
sip:ortm:. That counts asName:, so very few lines return?, far fewer than on the benchmark log. The named error and warning lines show the change clearly: pointers before,HttpClient,sres(the DNS resolver), andSipEventafter.In the benchmark (5M-line synthetic log, pinned to one fast core):
Measure Before After Change Python, component 1,501 ns/line 356 ns/line 4.2x faster Python, full pass 182k lines/s 231k lines/s +27% Rust, component 188 ns/line 58 ns/line 3.2x faster Rust, full single-thread pass 2.61M lines/s 4.06M lines/s +55% - In Rust, the gain came from using
is_matchplus a byte scan instead of capture groups. - Python and Rust gave byte-identical names for every line and identical counter output on the 5M-line log, a 200k-line sample, and two edge-case files.
Speed was the bonus. The real win is what the counts say:
Before After Top error sources 0x…a009.1k,?6.6k,0x…5405.0kHttpClient14.6k,sres(DNS resolver) 4.7k,?1.9kTop warning sources two pointers SipEvent,RegistrarWhen a counter trips, the model and the human both now see "HttpClient" instead of a pointer. That's far better context for the AI step: the model can say what is failing, not just that something at an address is. The unknown bucket for errors also shrank from 6.6k to 1.9k.
Caveats.
- 28% of benchmark lines still return
?, mostly header dumps and free text. That's fine for a counter, but don't read?as "no problem." - The one unexpected case was a lowercase "X module:" form, on 5.9% of lines. One more rule would catch it. I left that rule as an exercise: the
dns module:line ingen_log.pyand the matching edge case innames.pygive you a test case. Decide what that line should return, change the expected?inCASES, and make it pass. - The rules are tuned to synthetic formats. Check them on samples of your real lines before you trust them, especially function-style prefixes, other layouts, and multi-line messages.
- Only lines in the
Use the decision checklist
Before you rewrite a hot path in Rust, Go, or C, check these in order:
- Is it actually hot? Profile with cProfile or py-spy. If the model call is most of the time, a faster parser won't help.
- Can you do less work? Tighten patterns, match on fields instead of keywords, and drop counters nobody reads. This is almost always the first win.
- What's the worst case, not the average? Measure a burst, a backlog replay, and your expected fan-in, not just the steady rate.
- Do the threads starve each other? If the model call is late under load, look for lock and GIL contention before you blame the model.
- Can you prove the new version counts the same? Keep a fixed test log and diff the outputs on every change.
- Is the boundary simple? A CLI that prints lines or JSON, called with subprocess, is easier to run than a binding. Move to PyO3 only if per-call overhead shows up in the profile.
- Who maintains it? A Rust binary is one more toolchain for your team. With AI writing the code, that cost is lower than it used to be, but someone still reviews and ships it.
If you answer "yes, it's hot" to 1 and 3 and "no" to 2, the rewrite is probably worth it. Otherwise, keep Python and spend the time on the prompt.
Tips
Use
--releasefor every Rust timing. Debug builds can be many times slower and will make the comparison meaningless.Run each timing a few times and take the middle one. The first run often includes loading the file into the operating system's cache.
Keep the benchmark log synthetic or scrubbed. Real logs carry hostnames, addresses, and phone numbers that shouldn't end up in a repo or a blog post.
Ask your AI coding tool to port one function at a time and to keep the output format identical, so
diffcan check its work.
Common questions
Why not just use more Python processes?
You can. Splitting the file across processes with multiprocessing avoids the GIL for parsing. It doesn't remove the per-line interpreter overhead, though, and the model-calling side still needs care under bursts. Try it if your team would rather stay in one language, and measure it the same way.
Is a 14x speedup typical?
Don't count on it. The speedup depends on your patterns, your line lengths, and your CPU. That's why this guide gives you the code to measure your own instead of trusting mine.
Would Go have done as well?
Probably well enough here. Go's standard regexp package is often slower than Rust's regex crate, but either removes the Python interpreter from the hot path and the lock problem with it. The languages guide covers how to choose.
Is the memory map safe?
It's safe as long as nothing truncates the file while you read it, which is why Mmap::map is marked unsafe in Rust. For a log that's still being written, stream it line by line instead (for example, tail -F into the program's stdin), and use the memory map for replays and backlogs.
More guides
IntermediateGeneralProductivity
Five prompt patterns that get consistent results in any AI
Reusable prompt patterns for Claude, ChatGPT, Gemini, and Grok: role and goal, examples, step limits, structured output, and self-checks.
About 15 minutes using Claude, ChatGPT, Gemini, Grok
IntermediateGeneralPOC to production
Python, TypeScript, Go, or Rust? Pick the right language for each part of a production AI agent
AI writes the code now, so the skill that matters is choosing a language for each part of an agent and wiring in tools written in other languages.
About 30 minutes using uv (Python package and project manager), MCP official SDKs, vLLM OpenAI-compatible server, PyO3 and maturin, Python ctypes, py-spy profiler
AdvancedGeneralBuilding
Write simple evals to test your LLM app before you ship changes
Build a small eval set, score outputs with code checks and an LLM grader, and rerun it after every prompt or model change to catch regressions.
About 40 minutes using Claude API docs, OpenAI API docs