Python 3D Academyবাংলা

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, WARNING or ERROR
  • parse: turn a line of text into its parts, here with a regex and its groups

Step by step, the plan:

  1. Read: read_entries(lines) is a generator; for each line that fully matches the pattern, it yields (level, message) and quietly skips broken lines.
  2. Count: count_levels builds a Counter of levels; top_errors counts the ERROR messages and asks for most_common(n).
  3. Time: @timed wraps 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")
The broken line is skipped, ERROR appears 3 times, and disk full is the most common error. The timings are recorded without changing any result.

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, so top_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

  1. 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))
  2. What does this print?

    from collections import Counter
    levels = ["INFO", "ERROR", "ERROR", "WARNING", "ERROR"]
    print(Counter(levels).most_common(1))
  3. 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))
  4. 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
  5. 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

  1. Step 1: read the entries. Write the generator read_entries(lines). For each line that fully matches PATTERN (after .strip()), yield the tuple (level, message): groups 3 and 4. Skip lines that don't match.

  2. Step 2: count. Write count_levels(entries), returning a Counter of the levels, and top_errors(entries, n), returning the n most common ERROR messages as (message, count) pairs, using most_common.

  3. Step 3: time the reports. Write a decorator timed that runs the function, appends (function name, seconds taken) to the list TIMINGS (use time.perf_counter()), and returns the function's result unchanged. Put @timed on count_levels and top_errors.