Show contents
Chapter 6 of 7 · 25 min
Project: a server log analyser
By the end of this chapter, you'll be able to
- Design file processing as a pipeline of generators
- Represent immutable data with a frozen dataclass
- Count and rank with collections.Counter
- Set invalid lines aside without stopping the analysis
The log format
Each line describes a request: the date, the time, the HTTP method, the path requested, the status code and the processing time in milliseconds.
2026-11-02 08:14:03 GET /courses/python 200 120
Status codes fall into families: 2xx (success), 4xx (client error, such as a page that doesn't exist), 5xx (server error). A real log also contains damaged lines, for example after a power cut: the analysis must report them without stopping.
The final report is displayed; the file has already been closed.
Text description of the animation
- The file is opened, and its closing guaranteed whatever happens.
- The generator produces one line at a time.
- Each valid line becomes an immutable Request object.
- A badly formed line raises a ValueError, caught and noted: the pipeline carries on.
- The counters aggregate the requests.
- The final report is displayed; the file has already been closed.
The program
import functools
from collections import Counter
from contextlib import contextmanager
from dataclasses import dataclass
LOG = """\
2026-11-02 08:14:03 GET /courses/python 200 120
2026-11-02 08:14:09 GET /courses/java 200 98
2026-11-02 08:15:30 POST /login 401 15
line damaged by power cut
2026-11-02 08:16:02 GET /courses/python 200 131
2026-11-02 08:17:45 GET /images/logo.png 404 3
2026-11-02 08:18:10 GET /courses/python/quiz 500 870
2026-11-02 08:19:55 POST /login 200 22
"""
with open("access.log", "w", encoding="utf-8") as f:
f.write(LOG)
@dataclass(frozen=True)
class Request:
time: str
method: str
path: str
status: int
duration_ms: int
def count_calls(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return function(*args, **kwargs)
wrapper.calls = 0
return wrapper
@contextmanager
def open_log(path):
f = open(path, encoding="utf-8")
try:
yield f
finally:
f.close()
def lines(file):
for line in file:
if line.strip():
yield line.rstrip("\n")
@count_calls
def parse(line):
pieces = line.split()
if len(pieces) != 6:
raise ValueError(f"unexpected format: {line!r}")
_, time, method, path, status, duration = pieces
return Request(time, method, path, int(status), int(duration))
def requests(raw_lines, errors):
for line in raw_lines:
try:
yield parse(line)
except ValueError as error:
errors.append(str(error))
def report(path):
errors = []
with open_log(path) as f:
everything = list(requests(lines(f), errors))
statuses = Counter(r.status // 100 * 100 for r in everything)
pages = Counter(r.path for r in everything if r.method == "GET")
slow = [r.path for r in everything if r.duration_ms > 500]
print(f"{len(everything)} requests analysed, {len(errors)} line(s) skipped")
print("By status family:", dict(sorted(statuses.items())))
print("Most viewed page:", pages.most_common(1)[0])
print("Slow requests:", slow)
print("Rejected lines:", errors)
report("access.log")
print("parse called", parse.calls, "times")
7 requests analysed, 1 line(s) skipped
By status family: {200: 4, 400: 2, 500: 1}
Most viewed page: ('/courses/python', 2)
Slow requests: ['/courses/python/quiz']
Rejected lines: ["unexpected format: 'line damaged by power cut'"]
parse called 8 times
The choices worth noticing:
- Immutability.
Requestis afrozen=Truedataclass: once parsed, a request can no longer be changed by mistake. Immutable objects can be shared safely between several functions. - Errors on the side.
requestsreceives anerrorslist to fill: damaged lines are reported without breaking the pipeline. Countercounts the items of an iterable;most_common(1)gives the most frequent one.status // 100 * 100turns 404 into 400: the status family.- A function can carry attributes: the decorator stores its counter in
wrapper.calls. - The
\right after the three opening quotes ("""\) avoids an empty line at the start of the text.
Here, we materialise all the requests with list(...) to compute several statistics. On a log of several gigabytes, you'd update the counters as the pipeline flows, without ever keeping the whole list.
Your turn
Project: extend the analyserPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Worked exercise: the peak hour
From a sorted list of request times in the format "HH:MM:SS", build the dictionary {hour: number of requests} with groupby, then display the peak hour. With ["08:14:03", "08:14:09", "08:15:30", "09:02:11", "09:40:00", "11:05:59"], the result must be {'08': 3, '09': 2, '11': 1} and Peak hour: 08 h.
Hint 1
t[:2]. Since the list is sorted, requests from the same hour are neighbours.Hint 2
groupby group is an iterator: len(list(g)) counts its items.Show the solution and common mistakes
from itertools import groupby
times = ["08:14:03", "08:14:09", "08:15:30", "09:02:11", "09:40:00", "11:05:59"]
by_hour = {h: len(list(g)) for h, g in groupby(times, key=lambda t: t[:2])}
print(by_hour)
peak = max(by_hour.items(), key=lambda kv: kv[1])
print("Peak hour:", peak[0] + " h")
{'08': 3, '09': 2, '11': 1}
Peak hour: 08 h
Common mistakes:
- Using
groupbyon unsorted data: the same hour can appear in several groups, and the last occurrence overwrites the previous ones in the dictionary.Counter(t[:2] for t in times)doesn't have this flaw. - Writing
max(by_hour): you get the largest key ("11"), not the busiest hour.
Summary
- 1File processing is designed as a pipeline of generators.
- 2A frozen dataclass produces immutable objects, safe to share.
- 3Counter counts and ranks in one line; most_common gives the most frequent.
- 4Invalid lines are noted on the side, without stopping the analysis.
- 5A generator must be consumed before its resource is closed.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.