Skip to contentSkip to navigation

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, path and status.

  • Stream

    Generator stages read one line at a time, so a huge log uses little memory.

  • Count

    A Counter keeps 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

Tap any part of the code below, or press Next.1 of 6 explored

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.

Python
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"])
Output
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.

  1. lines = ["a 200", "bad", "b 500"]
  2. codes = []
  3. for line in lines:
  4. if " " in line:
  5. codes.append(line.split()[1])
  6. errors = [s for s in codes if s[0] == "5"]
  7. 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 notesOpen

Building the analyzer

The brief

The program reads a web server access log and prints a report: how many requests there were, how many lines could not be read, the count of each status code, the error rate, the three busiest client addresses and the slowest paths. It must handle a log of any size, and a single malformed line must not stop it.

One line, field by field

A typical access log line looks like this:

10.0.0.1 - - [27/Nov/2026:10:00:02 +0000] "GET /api/items HTTP/1.1" 500 87 1.250

Reading left to right: the client address, two fields that are usually a dash, the time in square brackets, the request in double quotes (method, path and protocol), the status code, the response size in bytes, and the time the server took in seconds. Writing the fields down like this before writing any pattern is the most useful step in the whole project.

One pattern with named groups

Each field becomes a piece of one regular expression. Named groups, written (?P<name>...), let the code read fields by name instead of by position:

Try it 1: edit me, then Run
import re

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.]+)$'
)
Output
Press Run to see what it prints.

Notice the careful pieces: \S+ means "anything up to the next space", [^\]]+ means "anything up to the closing bracket", and [^"]* means "anything up to the closing quote". Each is precise about where a field ends. A lazy .* would also work in many places, but explicit character classes make the pattern faster and its intent clearer. Compiling the pattern once with re.compile avoids rebuilding it for every line.

Parsing into records

A parse function turns a line into a dictionary of typed values, or returns None when the line does not match:

Try it 2: edit me, then Run
def parse(line):
    m = LINE.search(line.strip())
    if not m:
        return None
    return {
        "ip": m["ip"],
        "path": m["path"],
        "status": int(m["status"]),
        "size": 0 if m["size"] == "-" else int(m["size"]),
        "seconds": float(m["seconds"]),
    }
Output
Press Run to see what it prints.

Real logs hold surprises: a dash instead of a size for a redirect, a line cut short when the disk filled up, a request from a scanner full of junk. Returning None lets the caller count these lines as unreadable and carry on.

Streaming the file

Opening a file and looping over it reads one line at a time, so a generator stage can feed parsed records to the rest of the program while memory use stays tiny, even for a log of several gigabytes:

Try it 3: edit me, then Run
def records(path, bad):
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            record = parse(line)
            if record is None:
                bad.append(line)
            else:
                yield record
Output
Press Run to see what it prints.

errors="replace" keeps a stray invalid byte from stopping the whole run, as the encodings lesson explained.

Counting with Counter

collections.Counter was made for this job. One counter per question keeps the code short:

Try it 4: edit me, then Run
from collections import Counter

statuses, clients, total = Counter(), Counter(), 0
for r in records("access.log", bad):
    total += 1
    statuses[r["status"]] += 1
    clients[r["ip"]] += 1

print(clients.most_common(3))
Output
Press Run to see what it prints.

most_common(n) returns the top n pairs, highest count first. Because everything is counted in one pass, the file is read only once.

The error rate

Status codes come in families: 2xx success, 3xx redirect, 4xx client error, 5xx server error. Integer division finds the family: status // 100 is 5 for any code from 500 to 599. A server error rate is the share of requests in the 5xx family, and a client error rate the share in 4xx. Always check that total is not zero before dividing, so an empty log gives a report instead of a ZeroDivisionError.

The slowest requests

To find the slowest paths, keep the largest response time seen for each path, then sort by it. For a top few out of millions of lines, heapq.nlargest(3, items, key=...) avoids sorting everything. Average times hide spikes, so reporting the maximum, or better a high percentile, says more about what users actually felt.

Times and windows

The time field can be parsed with datetime.strptime(text, "%d/%b/%Y:%H:%M:%S %z"). Counting requests per hour with Counter(t.strftime("%H:00") for t in times) then shows when traffic peaks, and a sudden jump in errors within one window often points straight at a bad deploy.

The report

Like the word statistics project, build the report as a list of lines in one function and print it at the end. Keeping parsing, counting and printing separate means each part can be tested with a few lines typed into a list.

Ideas to extend it

Accept the log path as a command-line argument, read gzip-compressed logs with the gzip module, filter to one time window, or write the counts to a CSV file so they can be charted.

Syntax

The general shape of the statements in this lesson.

syntax.py
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 field
Output
Press 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

Intermediate

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.

Python
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))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The generator yields match objects and records the line numbers it could not read, so one broken line is reported rather than fatal. Everything is counted in a single pass. The error rates come from the status families using // 100, and :.0% formats a fraction as a whole percentage. A real version would guard total against zero before dividing.

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.

Buggy code: run it
import re
line = '"GET /a HTTP/1.1" 200 "Mozilla/5.0"'
print(re.search(r'"(.*)"', line).group(1))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints GET /a HTTP/1.1" 200 "Mozilla/5.0, running on to the last quote on the line

Write this instead

import re
line = '"GET /a HTTP/1.1" 200 "Mozilla/5.0"'
print(re.search(r'"([^"]*)"', line).group(1))

Why it happens

.* matches as much as it can, so the group stretches from the first quote to the last one.

In the real world

Where this shows up in software people use every day.

  1. Spotting a bad deploy

    Web operations

    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.

    Python
    import 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}")
    Output
    Press 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?

The structure does: only the pattern changes. Copy one real line, label its fields, and rewrite the pattern piece by piece, testing it on that line before running the whole file.

Should I use split() instead of a regular expression?

split() works for very simple formats, but the time and the quoted request contain spaces, so a split-based parser needs special cases. A pattern with named groups states the whole format in one place.

How do I read a compressed log?

Use gzip.open(path, "rt", encoding="utf-8"), which gives the same line-by-line text as open(), so the rest of the program is unchanged.

Is it safe to print client addresses?

IP addresses can identify people, so treat logs as personal data: keep reports internal, and shorten or remove addresses before sharing them more widely.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.