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.

5 min readUpdated 2026-11-30
In This Lesson
  • 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 StageTool UsedResponsibility
1. Pattern Matchre.compile + (?P<name>...)Extract ts, level, service, message or reject bad lines
2. Typed ModelLogLevel(str, Enum) + @dataclass(frozen=True)Guarantee valid severity levels and immutable records
3. Aggregationcollections.CounterCount errors per service cleanly with 0 defaults
4. Persistencepathlib.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) — restricts level strictly 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.
2 Common Lab Pitfalls to Watch Out For
  1. Calling .strip() before .search(): Trailing \n characters or leading spaces won't break ^...$ once you pass line.strip().
  2. Returning a Counter object directly when tests expect dict: While Counter is a dict subclass, wrapping with dict(counts) guarantees clean plain-dictionary output and JSON serialization.

Your Mission

Implement the following in the playground below:

  1. LogLevel(str, Enum) with values INFO, WARN, ERROR.
  2. @dataclass(frozen=True) class LogEntry with fields:
    • timestamp: datetime
    • level: LogLevel
    • service: str
    • message: str
  3. parse_line(line: str) -> LogEntry | None using LINE_RE.search(line.strip()) that converts ts via datetime.fromisoformat(...) and level via LogLevel(...), returning None on malformed/blank lines.
  4. summarize_errors(entries) returning a dict[str, int] counting how many LogLevel.ERROR entries occurred per service using Counter.
Python 3Lab 2: Build the Typed Log Parser
Output

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:

python
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

  1. Line 1 (INFO | auth | User logged in) matches LINE_RE → returns frozen LogEntry(..., level=LogLevel.INFO, service="auth", ...).
  2. Line 3 ("malformed garbage line") fails LINE_RE.search(...) → returns None and is cleanly filtered out by is not None.
  3. Lines 2, 5, and 6 match with LogLevel.ERROR (billing twice, auth once), so summarize_errors(parsed) produces {"billing": 2, "auth": 1} and writes formatted JSON to /tmp/error_summary.json.

Quick Troubleshooting Guide

SymptomLikely CauseFix
AssertionError: len(parsed) == 5Regex anchored without .strip() or LINE_RE.match failedUse LINE_RE.search(line.strip())
ValueError: Invalid isoformat stringMissing ts group or extra spacesPass data["ts"] directly to datetime.fromisoformat()
AttributeError: 'str' object has no attribute 'value'Stored raw string instead of LogLevel enumWrap 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)!

Check Your Understanding

In LINE_RE, why is the pipe character written as \\| instead of |?

Lab 2 Completion Checklist

0/3 done