4. Essential Standard Library for Real Projects
Practice Lab 2: Log Parser with Regex, Dataclasses & Pathlib
Combine Modules 3 and 4 in a realistic lab: build a frozen @dataclass LogEntry with an Enum level, parse raw server logs using compiled regex, and save a JSON summary via pathlib.
- Model parsed records cleanly using Enum and @dataclass(frozen=True)
- Parse structured log lines with re.compile and named capture groups
- Summarize counts with Counter and write reports safely using pathlib.Path
Time to combine Modules 3 and 4 into one clean, realistic engineering task!
You will build the core engine of a Server Log Parser that turns raw log lines into typed @dataclass objects, counts errors per service, and writes a JSON summary using pathlib.
Why This Lab Matters: Production Parsing Architecture
Instead of passing raw string splits or loose dictionaries around your codebase, clean Python pipelines convert messy text into validated, immutable domain objects at the boundary:
| Pipeline Stage | Tool Used | Responsibility |
|---|---|---|
| 1. Pattern Match | re.compile + (?P<name>...) | Extract ts, level, service, message or reject bad lines |
| 2. Typed Model | LogLevel(str, Enum) + @dataclass(frozen=True) | Guarantee valid severity levels and immutable records |
| 3. Aggregation | collections.Counter | Count errors per service cleanly with 0 defaults |
| 4. Persistence | pathlib.Path.write_text() | Persist the JSON report safely with UTF-8 encoding |
Decoding LINE_RE Piece by Piece
Notice how LINE_RE in the playground matches "2026-11-30T10:01:00+00:00 | INFO | auth | User logged in":
^(?P<ts>\S+)— captures the non-whitespace ISO timestamp at the start of the line.\s*\|\s*— matches a literal pipe|surrounded by optional spaces (remember\|escapes the regex OR symbol!).(?P<level>INFO|WARN|ERROR)— restrictslevelstrictly to valid severity names.(?P<service>\w+)— captures the alphanumeric service name (auth,billing).(?P<message>.+)$— captures the rest of the line up to the end.
- Calling
.strip()before.search(): Trailing\ncharacters or leading spaces won't break^...$once you passline.strip(). - Returning a
Counterobject directly when tests expectdict: WhileCounteris adictsubclass, wrapping withdict(counts)guarantees clean plain-dictionary output and JSON serialization.
Your Mission
Implement the following in the playground below:
LogLevel(str, Enum)with valuesINFO,WARN,ERROR.@dataclass(frozen=True) class LogEntrywith fields:timestamp: datetimelevel: LogLevelservice: strmessage: str
parse_line(line: str) -> LogEntry | NoneusingLINE_RE.search(line.strip())that convertstsviadatetime.fromisoformat(...)andlevelviaLogLevel(...), returningNoneon malformed/blank lines.summarize_errors(entries)returning adict[str, int]counting how manyLogLevel.ERRORentries occurred perserviceusingCounter.
Click “Run Code” to execute this snippet right in your browser.
How the Walrus Operator (:=) Works in the Lab Tests
Look at line 75 in the playground test block:
parsed = [entry for line in RAW_LOGS if (entry := parse_line(line)) is not None]The walrus operator (:=) assigns entry = parse_line(line) and checks entry is not None in a single expression—so parse_line(line) runs once per line instead of twice!
Step-by-Step Trace of RAW_LOGS
- Line 1 (
INFO | auth | User logged in) matchesLINE_RE→ returns frozenLogEntry(..., level=LogLevel.INFO, service="auth", ...). - Line 3 (
"malformed garbage line") failsLINE_RE.search(...)→ returnsNoneand is cleanly filtered out byis not None. - Lines 2, 5, and 6 match with
LogLevel.ERROR(billingtwice,authonce), sosummarize_errors(parsed)produces{"billing": 2, "auth": 1}and writes formatted JSON to/tmp/error_summary.json.
Quick Troubleshooting Guide
| Symptom | Likely Cause | Fix |
|---|---|---|
AssertionError: len(parsed) == 5 | Regex anchored without .strip() or LINE_RE.match failed | Use LINE_RE.search(line.strip()) |
ValueError: Invalid isoformat string | Missing ts group or extra spaces | Pass data["ts"] directly to datetime.fromisoformat() |
AttributeError: 'str' object has no attribute 'value' | Stored raw string instead of LogLevel enum | Wrap level with LogLevel(data["level"]) |
Bonus Challenge (Optional)
Once your assertions pass, add a second helper error_rate(entries: list[LogEntry]) -> float that returns the percentage of LogLevel.ERROR entries rounded to 1 decimal place (60.0 for 3 errors out of 5 valid lines)!
In LINE_RE, why is the pipe character written as \\| instead of |?