6. Final Capstone Project
Capstone Project: Production-Ready Log Analyzer & Report Pipeline
Build a clean, modular Python CLI pipeline combining generators, decorators, dataclasses, Enum, regex, pathlib, logging, context managers, and pytest.
- Combine generators, decorators, @dataclass, Enum, regex, pathlib, and logging in one architecture
- Stream large log files lazily without loading entire files into memory
- Test core pipeline functions cleanly with pytest and argparse
Welcome to the final capstone of Intermediate Python & Clean Code! You will build a clean, production-style Log Analyzer & Report Pipeline (log_analyzer.py) that brings together almost every tool from Modules 1–5:
Enum&@dataclass(frozen=True)for strongly typed log records- Compiled regex (
re.compile) with named capture groups - Lazy generator streaming (
yield) so even gigabyte-sized logs don't exhaust memory Counter&defaultdictfor fast aggregation- Custom
@timeddecorator &@contextmanagerfor observability pathlib.Path+logging+argparsefor a clean CLI- Automated
pytesttests to prove every piece works
1. Test the Core Engine Live in Your Browser
Run and inspect the streaming log analyzer engine directly in the Pyodide playground below before saving the full CLI project locally:
Click “Run Code” to execute this snippet right in your browser.
2. Full Local CLI Project (log_analyzer.py + test_log_analyzer.py)
Save log_analyzer.py locally to add logging and argparse CLI flags (--input, --output):
import argparse
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
import functools
import json
import logging
from pathlib import Path
import re
import time
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)-8s | %(message)s",
)
logger = logging.getLogger("log_analyzer")
class Level(str, Enum):
INFO = "INFO"
WARN = "WARN"
ERROR = "ERROR"
@dataclass(frozen=True)
class LogRecord:
timestamp: datetime
level: Level
service: str
latency_ms: int
message: str
LOG_RE = re.compile(
r"^(?P<ts>\S+)\s+(?P<level>INFO|WARN|ERROR)\s+"
r"service=(?P<service>\w+)\s+ms=(?P<ms>\d+)\s+(?P<msg>.+)$"
)
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed_ms = (time.perf_counter() - start) * 1000
logger.info("%s completed in %.2f ms", func.__name__, elapsed_ms)
return result
return wrapper
def parse_line(line: str) -> LogRecord | None:
match = LOG_RE.search(line.strip())
if not match:
return None
d = match.groupdict()
return LogRecord(
timestamp=datetime.fromisoformat(d["ts"]),
level=Level(d["level"]),
service=d["service"],
latency_ms=int(d["ms"]),
message=d["msg"],
)
def stream_records(path: Path):
with path.open("r", encoding="utf-8") as fh:
for line in fh:
record = parse_line(line)
if record is not None:
yield record
@timed
def build_report(input_dir: Path) -> dict:
level_counts: Counter[str] = Counter()
errors_by_service: Counter[str] = Counter()
latencies: defaultdict[str, list[int]] = defaultdict(list)
for log_file in sorted(input_dir.rglob("*.log")):
logger.info("Scanning %s", log_file)
for rec in stream_records(log_file):
level_counts[rec.level.value] += 1
latencies[rec.service].append(rec.latency_ms)
if rec.level == Level.ERROR:
errors_by_service[rec.service] += 1
return {
"levels": dict(level_counts),
"errors_by_service": dict(errors_by_service),
"avg_latency_ms": {
svc: round(sum(vals) / len(vals), 1) for svc, vals in latencies.items()
},
}
def main():
parser = argparse.ArgumentParser(description="Analyze .log files into JSON.")
parser.add_argument("--input", type=Path, required=True, help="Folder of .log files")
parser.add_argument("--output", type=Path, default=Path("report.json"))
args = parser.parse_args()
report = build_report(args.input)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2), encoding="utf-8")
logger.info("Wrote report to %s", args.output)
if __name__ == "__main__":
main()Automated pytest Suite (test_log_analyzer.py)
import pytest
from log_analyzer import Level, build_report, parse_line
@pytest.mark.parametrize(
"line, expected_level",
[
("2026-11-30T10:00:00+00:00 INFO service=auth ms=12 Ok", Level.INFO),
("2026-11-30T10:00:01+00:00 ERROR service=pay ms=300 Timeout", Level.ERROR),
],
)
def test_parse_valid_lines(line, expected_level):
rec = parse_line(line)
assert rec is not None
assert rec.level == expected_level
def test_parse_malformed_returns_none():
assert parse_line("not a valid log line") is None
def test_build_report_with_tmp_path(tmp_path):
log_file = tmp_path / "service.log"
log_file.write_text(
"2026-11-30T10:00:00+00:00 ERROR service=api ms=200 Crash\n"
"2026-11-30T10:00:01+00:00 INFO service=api ms=40 Healthy\n",
encoding="utf-8",
)
report = build_report(tmp_path)
assert report["errors_by_service"] == {"api": 1}
assert report["avg_latency_ms"]["api"] == 120.0Run it locally with:
pytest -v
python3 log_analyzer.py --input ./logs --output ./out/report.jsonCapstone Checklist & Next Steps
Intermediate Python Capstone Checklist
0/4 doneReady to earn your certificate? Head to the Final Assessment to test your mastery across all 6 modules!