Project: a log analyser
🌍 In real life. A shop's website writes a line to a log file every time something happens: a customer logs in, a page is slow, the disk is full. On a busy day there are thousands of lines, and some are broken. When the site misbehaves, the owner wants quick answers: how many errors were there, and which error happened most?
In this project you'll build that log analyser with tools from World 5: a generator, a regular expression, Counter, and a decorator that times the work.
The plan in one sentence: a generator reads the log line by line and yields only the lines that fit a pattern, Counter adds them up, and a decorator records how long each report takes.
Its words:
- log entry: one line, like
2026-10-17 09:15:07 ERROR disk full: date, time, level, message - level: how serious it is:
INFO,WARNINGorERROR - parse: turn a line of text into its parts, here with a regex and its groups
Step by step, the plan:
- Read:
read_entries(lines)is a generator; for each line that fully matches the pattern, it yields(level, message)and quietly skips broken lines. - Count:
count_levelsbuilds aCounterof levels;top_errorscounts the ERROR messages and asks formost_common(n). - Time:
@timedwraps both counting functions and records(name, seconds)for every call.
Here's the pattern picking a log line apart into its four groups:
Step 1: read lazily. A log can be bigger than memory, so read_entries is a generator (Lesson 26.2): it takes any iterable of lines, even an open file, and yields one entry at a time. fullmatch (Lesson 31.2) makes sure the whole line fits, so a broken line is skipped instead of half-matched.
Step 2: count. A Counter (Lesson 30.1) of levels answers "how many errors?" in one line, and most_common(n) answers "which error happened most?".
Step 3: time it. @timed (Chapter 27) wraps a function with *args, **kwargs, so it fits both counting functions, measures with time.perf_counter(), and appends (func.__name__, seconds) to a list.
import re
import time
from collections import Counter
PATTERN = re.compile(r"(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (INFO|WARNING|ERROR) (.+)")
TIMINGS = []
def timed(func):
"""Record each call's function name and how many seconds it took."""
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
TIMINGS.append((func.__name__, time.perf_counter() - start))
return result
return wrapper
def read_entries(lines):
"""Yield (level, message) for every line that fits the log format."""
for line in lines:
m = PATTERN.fullmatch(line.strip())
if m:
yield m.group(3), m.group(4)
@timed
def count_levels(entries):
"""How many entries there are of each level."""
return Counter(level for level, _ in entries)
@timed
def top_errors(entries, n):
"""The n most common error messages, with their counts."""
errors = Counter(message for level, message in entries if level == "ERROR")
return errors.most_common(n)
with open("server.log") as f:
entries = list(read_entries(f))
print(count_levels(entries))
print(top_errors(entries, 1))
for name, seconds in TIMINGS:
print(name, "took", "under a second" if seconds < 1 else "a while")Why build it this way, and what it costs. Each piece does one job and can be tested with a short list instead of a real log. The whole analysis is one pass to read plus one pass per report, so a log of a million lines takes about a few million steps, and because reading is lazy, memory stays small if you count straight from the generator. The decorator adds two clock readings per call, which is nothing next to the counting.
Mistakes and edge cases.
- search instead of fullmatch. A line with extra junk at the start would still be half-matched and counted.
- Using the generator twice.
count_levels(entries)uses it up, sotop_errors(entries, 1)on the same generator finds nothing; make a list first, as the example does, or read the file again. - A wrapper that forgets to return. Then every timed function gives back
None. - Timing in tests. Seconds change from run to run, so check that a timing was recorded, not its exact value.
Quiz
What does this print?
import re m = re.fullmatch(r"(\d\d:\d\d) (INFO|ERROR) (.+)", "09:15 ERROR disk full") print(m.group(2), "|", m.group(3))What does this print?
from collections import Counter levels = ["INFO", "ERROR", "ERROR", "WARNING", "ERROR"] print(Counter(levels).most_common(1))top_errors finds nothing, though the log has errors. Which line causes it?
entries = read_entries(open("server.log")) print(count_levels(entries)) print(top_errors(entries, 1))Why does read_entries use fullmatch instead of search?
- So a broken line is skipped instead of being half-matched
- Because search can't use groups
- Because fullmatch is a generator
What does this print?
calls = [] def logged(func): def wrapper(*args): calls.append(func.__name__) return func(*args) return wrapper @logged def double(n): return n * 2 print(double(4), calls)
Coding tasks
Step 1: read the entries. Write the generator
read_entries(lines). For each line that fully matchesPATTERN(after.strip()), yield the tuple(level, message): groups 3 and 4. Skip lines that don't match.Step 2: count. Write
count_levels(entries), returning aCounterof the levels, andtop_errors(entries, n), returning thenmost common ERROR messages as(message, count)pairs, usingmost_common.Step 3: time the reports. Write a decorator
timedthat runs the function, appends(function name, seconds taken)to the listTIMINGS(usetime.perf_counter()), and returns the function's result unchanged. Put@timedoncount_levelsandtop_errors.