Parsing log lines with named groups
Build one real pattern from a sample access-log line, field by field, with named groups, per-field tests, and a plan for the lines that do not fit.
Named capture groupsCapturing groups and numberingNegated classesAnchors and line boundariesValidating input: emails, URLs and addresses
Parsing log lines with named groups
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Build a log pattern one field at a time, test after each addition, and anchor the whole thing with ^ and $ so a partial match cannot slip through.
- Named groups make the pattern read like a schema and the result like a record: m.groups.status instead of m[7]. In JavaScript the groups object has no prototype, and a group that did not take part is undefined.
- Write each field with the narrowest class that fits: \S+ for a token, [^\]]+ for a bracketed time, [^"]*? inside quotes. Avoid .* between fields.
- Expect bad lines. A failed match returns null, so count and keep the failures instead of crashing. My test file had 200 bad lines in 200,000, found in 62 ms.
- A sloppy (.*) (.*) (.*) pattern mis-split a line with a second quoted part and took 2.4 seconds on a 4,000-character line. The strict one rejected it in 0.01 ms.
One line, nine fields
A server writes a line per request and you want the status codes. Here is a line in the shape of Apache’s common log format, with an ISO timestamp:
10.0.0.5 - alice [2026-11-03T21:33:00Z] "POST /api/login HTTP/1.1" 200 312
Reading it as a person, you see an address, two identity fields (- means none), a time in brackets, a quoted request, a status and a byte count. A regex lets you say the same thing to a program. The trick is to build it the way you read it, one field at a time, running it after each step. I did this in Node 26.
Build it up
Step one is just the address:
/^(?<ip>\S+) /
// { ip: '198.51.100.4' }
(?<ip>...) names the group, and \S+ takes a run of non-space characters. Adding the two identity fields and the bracketed time:
/^(?<ip>\S+) (?<ident>\S+) (?<user>\S+) \[(?<time>[^\]]+)\]/
// { ip: '10.0.0.5', ident: '-', user: 'alice', time: '2026-11-03T21:33:00Z' }
The time is [^\]]+: any characters except the closing bracket. That is the narrowest thing that works, and it stops exactly where the field ends. Then the request line:
... "(?<method>[A-Z]+) (?<path>\S+) (?<proto>HTTP\/\d(?:\.\d)?)"
// method 'POST', path '/api/login', proto 'HTTP/1.1'
Each step either gave the fields I expected or it did not, and I knew which new piece to look at. This is the whole technique: never write the full pattern first.
The finished pattern
const log = /^(?<ip>\S+) (?<ident>\S+) (?<user>\S+) \[(?<time>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)\] "(?:(?<method>[A-Z]+) (?<path>[^"]*?) (?<proto>HTTP\/\d(?:\.\d)?)|-)" (?<status>\d{3}) (?<bytes>\d+|-)$/;
I tightened three places. The time is now a real shape. The path is [^"]*?, which allows spaces (my test line GET /search?q=a b HTTP/1.1 had one) but cannot cross a quote. And the request is an alternation: either method, path and protocol, or just "-", which I understand servers log when a client connects and never sends a request (from memory, not checked). I fed it eight lines:
{"ip":"198.51.100.4", "time":"2026-11-02T13:49:00Z", "method":"GET", "path":"/index.html", "status":404, "bytes":5281}
{"ip":"10.0.0.7", ..., "path":"/static/app.js", "proto":"HTTP/2.0", "status":304, "bytes":null}
{"ip":"203.0.113.9", "time":"2026-11-04T09:02:00Z", "status":408, "bytes":0}
{"ip":"10.0.0.5", ..., "path":"/search?q=a b", "status":200, "bytes":51}
NO MATCH: "10.0.0.5 - - [2026-11-04T09:04:00Z] \"GET /ok HTTP/1.1\" 200"
NO MATCH: "garbage line"
NO MATCH: ""
bytes is - when no body was sent, so I mapped that to null. The request-"-" line produced no method or path at all. In JavaScript, m.groups is an object with a null prototype, and a group that did not take part is undefined, which I confirmed. Python’s (?P<name>...) returned None for the same line, and groupdict() gave me the record.
Test the fields on their own
A long pattern is hard to debug as a whole, so keep each field’s pattern separate and test it alone against good and bad values. The IPv4 octet pattern from the validation lesson accepted 198.51.100.4 and rejected 198.51.100.400, and ^[1-5]\d\d$ accepted 404 and rejected 999. If you need the stricter field in the log pattern, substitute it in. Then run the whole thing on a file with known good and bad counts.
Handle the lines that do not fit
Real logs contain truncated lines, partial writes and garbage. When exec returns null, do not let it crash a loop or vanish silently. I generated 200,000 lines, one in a thousand corrupted, and counted:
200000 lines: good=199800 bad=200 {"200":66600,"404":66600,"500":66600} 62 ms
Exactly the 200 corrupted lines failed. Keeping them (or a sample) tells you the day your logging format changes.
Why not (.*) (.*) (.*)?
The tempting shortcut is dots everywhere: /^(.*) (.*) (.*) \[(.*)\] "(.*)" (\d+) (\d+|-)$/. It matches the clean lines. On a line with a second quoted part, GET /a" 200 5 "x" 301 7, it matched and mis-split it: it reported status 301 and bytes 7, taking everything between the first and last quote as the request. My strict pattern returned null for that line, which is the correct verdict. The sloppy one is also slow. On a line of 2,000 repeated a tokens (4,001 characters) it took 2,367 ms warm, and about eight times longer for each doubling of length in my runs from 500 to 2,000 tokens. The strict pattern took 0.01 ms to reject a 50,000-character malformed line. Narrow classes are both more correct and faster, which is lesson 40 again.
About the video
“Log File Parsing In Python (Part 1)” by Roberts Greibers was published 8 April 2023 and runs 14 minutes 5 seconds. Its chapters are “Introduction to log parsing”, “Reading the log file”, “Identifying log patterns”, “Crafting regular expressions”, “Implementing the parser” and “Testing with regex101”. That order is the same workflow as above, and it uses regex101 for testing. The description is only links and a part 2 pointer, and I couldn’t read a transcript, so I can’t say whether it uses named groups, how it deals with malformed lines, or which Python version it targets. It is in Python and this lesson’s main examples are JavaScript. English per its title and description.
What I did not run
Part 2 of the video, the regex101 workflow, real Apache or nginx logs (my lines are synthetic, shaped like common log format), and multi-line log records such as stack traces.
Next
Logs mostly stay between quotes. Quoted strings and CSV fields handles quotes that contain quotes.
Check yourself
Why anchor a log-line pattern with ^ and $?
Without them, a pattern can match a fragment in the middle of a longer or malformed line and hand you plausible-looking wrong data. Anchoring makes the pattern describe the whole line or fail, so bad lines are visible.
In my pattern the request part is (?:(?<method>...) ...|-). What do m.groups.method and m.groups.path hold for a line whose request is just "-"?
Both are undefined, because the alternative that defines them did not take part in the match. Python gives None for the same case. Handle that before using them.
Why is [^\]]+ better than .+ for the bracketed timestamp?
It cannot run past the closing bracket, so it stops where the field ends and cannot swallow later parts of the line. A greedy .+ would take as much as possible and then back off, which both mis-splits lines and costs time.
How do you handle lines that do not match?
Treat the null result as data: count the failures, keep a sample of them, and decide whether to skip or alarm. Silently dropping them hides a format change in your logs.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.