Module 18 · Lesson 01
Project: Server Log Analyzer
Build a log analyzer: parse web server access lines with a regular expression, stream them through generator stages, and report status codes, the error rate, the busiest clients and the slowest paths.
- About 10 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Parse, stream, count, report
- Read a field by name
- Build the analyzer in five steps
- Watch lines become a report
The analyzer in four parts
Log lines go in, a report comes out. Each part is one small function you can test on its own.
Parse
One pattern with named groups turns a line into fields such as
ip,pathandstatus.Stream
Generator stages read one line at a time, so a huge log uses little memory.
Count
A
Counterkeeps how often each status code and each client appears.Report
Totals, the error rate, the busiest clients and the slowest paths.
Logs everywhere
Every website, app and game server writes lines like these.
- Site dashboardsVisitor counts and popular pages come from access logs.
- Outage alarmsA sudden jump in 5xx errors wakes up the person on call.
- Security checksOne address asking for hundreds of login pages stands out in the counts.
- Game serversSlow requests show which part of the game makes players wait.
Is this line an error?
This line decides whether a request failed on the server. Tap each part to see its job.
Part 1 of 6
flag:True when the server itself failed on this request.
Build the analyzer in five steps
Build the project one step at a time. Each example runs on its own: change it, then press Run.
Example 1 of 61. Parse
One pattern, one named group per field.
Your turn: Print m.groupdict() to see every field at once.
import re
LINE = re.compile(r'(?P<ip>\S+) "(?P<method>[A-Z]+) (?P<path>\S+)" (?P<status>\d{3}) (?P<seconds>[\d.]+)')
line = '10.0.0.1 "GET /api/items" 500 1.250'
m = LINE.match(line)
print(m["ip"], m["path"], m["status"], m["seconds"])Press Run to see what it prints.Watch lines become a report
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- lines = ["a 200", "bad", "b 500"]
- codes = []
- for line in lines:
- if " " in line:
- codes.append(line.split()[1])
- errors = [s for s in codes if s[0] == "5"]
- print(codes, len(errors))
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.A line that does not fit:
import re
print(re.match(r"\d{3}", "abc"))0 of 6 answered
Common analyzer misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
re.compile(r"(?P<ip>\S+) ... (?P<status>\d{3})") # one pattern, named groups
m = LINE.search(line); m["status"] # read a group by name
for line in open(path, encoding="utf-8", errors="replace"): # stream the file
Counter(); c[key] += 1; c.most_common(3) # count and rank
status // 100 == 5 # server error family
errors / total if total else 0.0 # guard the rate
heapq.nlargest(3, items, key=lambda p: p[1]) # top few without a full sort
datetime.strptime(t, "%d/%b/%Y:%H:%M:%S %z") # parse the time fieldPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
The complete analyzer
Write a small sample log to a file, then stream it through a parse stage, count statuses and clients, work out the error rates and print a report that also counts unreadable lines.
import re
from collections import Counter
from pathlib import Path
LINE = re.compile(
r'(?P<ip>\S+) \S+ \S+ \[(?P<time>[^\]]+)\] '
r'"(?P<method>[A-Z]+) (?P<path>\S+) [^"]*" '
r'(?P<status>\d{3}) (?P<size>\d+|-) (?P<seconds>[\d.]+)$'
)
Path("access.log").write_text("""\
10.0.0.1 - - [27/Nov/2026:10:00:01 +0000] "GET / HTTP/1.1" 200 512 0.020
10.0.0.2 - - [27/Nov/2026:10:00:02 +0000] "GET /api/items HTTP/1.1" 500 87 1.250
10.0.0.1 - - [27/Nov/2026:10:00:03 +0000] "POST /login HTTP/1.1" 302 - 0.110
broken line
10.0.0.3 - - [27/Nov/2026:10:00:05 +0000] "GET /missing HTTP/1.1" 404 0 0.005
10.0.0.1 - - [27/Nov/2026:10:00:06 +0000] "GET /api/items HTTP/1.1" 200 2048 0.840
""", encoding="utf-8")
def records(path, bad):
with open(path, encoding="utf-8", errors="replace") as f:
for number, line in enumerate(f, start=1):
m = LINE.search(line.strip())
if m:
yield m
else:
bad.append(number)
bad = []
statuses, clients = Counter(), Counter()
for m in records("access.log", bad):
statuses[int(m["status"])] += 1
clients[m["ip"]] += 1
total = sum(statuses.values())
server = sum(n for code, n in statuses.items() if code // 100 == 5)
client = sum(n for code, n in statuses.items() if code // 100 == 4)
print(f"Requests: {total}, unreadable lines: {bad}")
print("Statuses:", dict(sorted(statuses.items())))
print(f"Server errors: {server / total:.0%}, client errors: {client / total:.0%}")
print("Busiest:", clients.most_common(2))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
A greedy pattern swallows several fields
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
import re line = '"GET /a HTTP/1.1" 200 "Mozilla/5.0"' print(re.search(r'"(.*)"', line).group(1))
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Web operations
Spotting a bad deploy
An online shop deploys new code several times a day. A short script run after each deploy counts server errors per minute from the access log, so a sudden spike is noticed before customers start complaining.
Why Python fits
This pattern captures only the two fields the check needs: the hour and minute, and the status. Counting 5xx responses per minute turns a long log into a few lines, and the threshold flags the minute right after the deploy when checkout began to fail.
Pythonimport re from collections import Counter LOG = [ '10.1.1.5 - - [27/Nov/2026:14:01:10 +0000] "GET /cart HTTP/1.1" 200 900 0.08', '10.1.1.6 - - [27/Nov/2026:14:01:40 +0000] "GET /cart HTTP/1.1" 200 880 0.09', '10.1.1.7 - - [27/Nov/2026:14:02:05 +0000] "POST /checkout HTTP/1.1" 502 0 3.01', '10.1.1.5 - - [27/Nov/2026:14:02:20 +0000] "POST /checkout HTTP/1.1" 502 0 3.00', '10.1.1.8 - - [27/Nov/2026:14:02:31 +0000] "GET /cart HTTP/1.1" 500 0 0.40', '10.1.1.9 - - [27/Nov/2026:14:03:02 +0000] "GET /cart HTTP/1.1" 200 870 0.07', ] PATTERN = re.compile(r':(?P<minute>\d\d:\d\d):\d\d .*" (?P<status>\d{3}) ') errors = Counter() for line in LOG: m = PATTERN.search(line) if m and m["status"].startswith("5"): errors[m["minute"]] += 1 for minute, count in sorted(errors.items()): flag = " <- investigate" if count >= 3 else "" print(f"{minute} {count} server errors{flag}")OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
My server's log format is different. Does the project still work?
Should I use split() instead of a regular expression?
How do I read a compressed log?
Is it safe to print client addresses?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.