Skip to content

09. Standard library power tools — Mini-project

The data team runs a pipeline and a prediction API. Both write to one log file. Every morning, the on-call engineer opens the log and answers the same questions by hand: how many requests failed, how slow was the API, did every pipeline run finish, did the model score drop, and which errors happened when?

Write ops_report.py, a script that answers these questions in a short report. The engineer works in Chicago, a colleague in Berlin. So the script shows times in a time zone chosen with the environment variable REPORT_TZ. It prints the report and saves it as a text file that can be attached to a ticket. The report leaves the team, so it must not contain full email addresses.

The project uses most of module 09: re with named groups and re.VERBOSE, datetime and zoneinfo, Counter, defaultdict and namedtuple, statistics, os.environ, sys.exit and pathlib.

data/logs/app.log holds 500 lines from 2024-05-01, 08:04 to 19:57 UTC. Two kinds of lines matter:

2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms user=mei.chen@example.org
2024-05-01 08:25:13,663 INFO [pipeline] Starting pipeline run-0001 config=data/config.json

Every normal line has a timestamp with milliseconds, a level (DEBUG, INFO, WARNING, ERROR), a component in brackets and a message. API messages have the form <ip> <METHOD> <path> <status> <ms>ms user=<email or ->. The pipeline writes Starting pipeline run-NNNN and Finished run-NNNN status=success, and the model writes roc_auc=0.8xx. 8 lines belong to two Python tracebacks and have no timestamp. The timestamps are in UTC.

Your script must:

  1. Read the time zone from REPORT_TZ (default UTC) and the output folder from REPORT_DIR (default output). An unknown time zone ends the script with a clear message and exit code 1, through sys.exit().
  2. Parse each timestamped line with one compiled regex that uses named groups, into a namedtuple. Make every timestamp an aware datetime in UTC. Count the lines without a timestamp.
  3. Count the lines per level with a Counter.
  4. For the API: the number of requests, the count and share of 4xx and 5xx responses, the median, 95th percentile and maximum latency, the busiest endpoint (ignore the query string) and every user with 2 or more 429 responses, sorted by count (largest first), then by email.
  5. For the pipeline: the runs started and finished, the mean and the longest duration, and the minimum and maximum roc_auc with the number of runs below 0.820.
  6. List every ERROR line with its clock time in the report’s time zone.
  7. Mask every email as its first letter, *** and the domain.
  8. Print the report and write it to <REPORT_DIR>/ops_report.txt. Print only relative paths.
  9. Put the work in functions and call main() under if __name__ == "__main__":.

The report for the default settings:

Expected output
Operations report for 2024-05-01 (times in UTC)
===============================================
Log lines: 500 (8 traceback lines)
Levels: INFO 447, WARNING 25, DEBUG 13, ERROR 7
API requests: 391
Client errors (4xx): 51 (13.0%)
Server errors (5xx): 3 (0.8%)
Latency median / p95 / max: 40 / 221 / 1334 ms
Busiest endpoint: /api/v1/products (113 requests)
Users with 2+ rate-limited (429) requests: 5
a***@example.com 3
d***@example.net 2
l***@example.net 2
p***@example.com 2
t***@example.org 2
Pipeline runs: 9 started, 9 finished
Duration mean 5.72 s, longest run-0005 (11.55 s)
roc_auc min 0.812, max 0.844; 3 of 9 below 0.820
Errors:
10:37:08 [db] OperationalError: database is locked (attempt 1/3), retrying in 1s
10:53:55 [db] OperationalError: database is locked (attempt 1/3), retrying in 1s
10:53:56 [loader] Failed to parse data/reports/2024-04.csv
15:35:27 [loader] Failed to parse data/reports/2024-04.csv
17:18:02 [api] 198.51.100.23 POST /api/v1/predict 500 1188ms user=p***@example.com
18:28:00 [api] 203.0.113.45 GET /api/v1/products?page=2 500 1334ms user=p***@example.com
19:34:34 [api] 10.0.3.17 GET /api/v1/products?page=2 500 974ms user=t***@example.org
Report written to output/ops_report.txt
  1. Read one line by hand. In the REPL, copy one API line and one pipeline line. Write the line regex with re.VERBOSE and test it with match() on both.

  2. Parse the file. Write parse_log(path) that returns a list of Entry named tuples and the count of lines that do not match. Turn the timestamp into an aware datetime with datetime.fromisoformat(...).replace(tzinfo=UTC).

  3. Summarize the API. Write a second regex for the API message. Collect the matches, then use Counter for the status classes (status // 100), the endpoints and the 429 users. Sort the users with a key that gives a fixed order for ties: (-count, email). statistics.quantiles(latency, n=20)[-1] is the 95th percentile.

  4. Summarize the runs. Search each message for Starting pipeline run-NNNN and Finished run-NNNN. Store the two timestamps per run in a defaultdict(dict). Subtract them for the duration.

  5. Build the report. Write build_report(entries, other, zone) that returns a list of lines. Convert each displayed time with astimezone(zone). Mask emails with re.sub().

  6. Wire up main(). Read the two environment variables, catch ZoneInfoNotFoundError and call sys.exit() with a message, write the file, print the report.

  7. Run it three ways: with no settings, with REPORT_TZ=America/Chicago, and with an invalid zone. Compare the first run with the expected report.

Criterion Points Full points when
Runs as a script 2 python ops_report.py prints the report and writes output/ops_report.txt
Parsing 3 One compiled regex with named groups; aware UTC datetimes; traceback lines counted, not crashed on
Correct numbers 3 Every count, share, latency and duration matches the expected report
Collections 2 Counter, defaultdict and namedtuple used where each fits
Time zones 2 REPORT_TZ changes every displayed time; stored times stay in UTC
Privacy 1 No full email address appears in the report
Settings and errors 2 Defaults for both variables; an invalid zone exits with code 1 and a clear message
Structure 1 Functions, a main() and the main guard; ruff-clean
Total 16 13 or more: you are ready for the Part 1 checkpoint
  1. Add --tz and --out command-line options with argparse (module 08). The option wins over the environment variable, which wins over the default.
  2. Exit with code 2 when the 5xx share is above 1%, so that a scheduler can raise an alert.
  3. Group the 429 responses into 10-minute windows with groupby on the rounded timestamp, and report the busiest window.
  4. Mask the IP addresses too, as in exercise M09-C13.
  5. Write the summary numbers as JSON next to the text report, so that a dashboard can read them.

Try the project yourself first. Then compare your script with this one. Your structure and names can differ; your report must not.

Reference solution
ops_report.py
"""ops_report.py: a daily operations report from data/logs/app.log.
Settings come from environment variables:
REPORT_TZ time zone for displayed times (default: UTC)
REPORT_DIR folder for the report file (default: output)
"""
import os
import re
import statistics
import sys
from collections import Counter, defaultdict, namedtuple
from datetime import UTC, datetime
from pathlib import Path
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
LOG_PATH = Path("data/logs/app.log")
AUC_THRESHOLD = 0.820
Entry = namedtuple("Entry", ["stamp", "level", "component", "message"])
LINE = re.compile(
r"""
^(?P<stamp>\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2},\d{3})\s
(?P<level>[A-Z]+)\s
\[(?P<component>\w+)\]\s
(?P<message>.*)$
""",
re.VERBOSE,
)
REQUEST = re.compile(
r"(?P<ip>[\d.]+) (?P<method>GET|POST) (?P<path>\S+) "
r"(?P<status>\d{3}) (?P<ms>\d+)ms user=(?P<user>\S+)"
)
RUN = re.compile(r"(?P<event>Starting pipeline|Finished) (?P<run>run-\d{4})")
AUC = re.compile(r"roc_auc=(?P<auc>[\d.]+)")
EMAIL = re.compile(r"(\w)[\w.]*@([\w.]+)")
def parse_log(path):
"""Return the timestamped entries and the number of other lines."""
entries, other = [], 0
with open(path, encoding="utf-8") as f:
for raw in f:
match = LINE.match(raw.rstrip("\n"))
if match is None:
other += 1 # traceback lines have no timestamp
continue
stamp = datetime.fromisoformat(match["stamp"]).replace(tzinfo=UTC)
entries.append(
Entry(stamp, match["level"], match["component"], match["message"])
)
return entries, other
def summarize_api(entries):
requests = []
for entry in entries:
found = REQUEST.fullmatch(entry.message)
if entry.component == "api" and found is not None:
requests.append(found.groupdict())
statuses = Counter(int(r["status"]) // 100 for r in requests)
latency = sorted(int(r["ms"]) for r in requests)
endpoints = Counter(r["path"].split("?")[0] for r in requests)
limited = Counter(r["user"] for r in requests if r["status"] == "429")
return requests, statuses, latency, endpoints, limited
def summarize_runs(entries):
times = defaultdict(dict)
aucs = []
for entry in entries:
run = RUN.search(entry.message)
if run is not None:
times[run["run"]][run["event"]] = entry.stamp
auc = AUC.search(entry.message)
if auc is not None:
aucs.append(float(auc["auc"]))
durations = {
run: (events["Finished"] - events["Starting pipeline"]).total_seconds()
for run, events in times.items()
if "Finished" in events
}
return times, durations, aucs
def mask(text):
return EMAIL.sub(r"\1***@\2", text)
def build_report(entries, other, zone):
lines = []
day = entries[0].stamp.astimezone(zone).date()
title = f"Operations report for {day} (times in {zone.key})"
lines += [title, "=" * len(title)]
levels = Counter(entry.level for entry in entries)
lines.append(f"Log lines: {len(entries) + other} ({other} traceback lines)")
lines.append("Levels: " + ", ".join(f"{k} {v}" for k, v in levels.most_common()))
requests, statuses, latency, endpoints, limited = summarize_api(entries)
p95 = statistics.quantiles(latency, n=20)[-1]
lines.append("")
lines.append(f"API requests: {len(requests)}")
for group, label in [(4, "Client errors (4xx)"), (5, "Server errors (5xx)")]:
share = statuses[group] / len(requests)
lines.append(f" {label}: {statuses[group]} ({share:.1%})")
lines.append(
f" Latency median / p95 / max: {statistics.median(latency):.0f} / "
f"{p95:.0f} / {latency[-1]} ms"
)
path, count = endpoints.most_common(1)[0]
lines.append(f" Busiest endpoint: {path} ({count} requests)")
repeat = sorted(
(item for item in limited.items() if item[1] >= 2),
key=lambda item: (-item[1], item[0]), # count, largest first; then email
)
lines.append(f" Users with 2+ rate-limited (429) requests: {len(repeat)}")
lines += [f" {mask(user)} {n}" for user, n in repeat]
times, durations, aucs = summarize_runs(entries)
longest = max(durations, key=durations.get)
low = sum(auc < AUC_THRESHOLD for auc in aucs)
lines.append("")
lines.append(f"Pipeline runs: {len(times)} started, {len(durations)} finished")
lines.append(
f" Duration mean {statistics.mean(durations.values()):.2f} s, "
f"longest {longest} ({durations[longest]:.2f} s)"
)
lines.append(
f" roc_auc min {min(aucs):.3f}, max {max(aucs):.3f}; "
f"{low} of {len(aucs)} below {AUC_THRESHOLD:.3f}"
)
lines.append("")
lines.append("Errors:")
for entry in entries:
if entry.level == "ERROR":
local = entry.stamp.astimezone(zone).strftime("%H:%M:%S")
lines.append(f" {local} [{entry.component}] {mask(entry.message)}")
return lines
def main():
zone_name = os.environ.get("REPORT_TZ", "UTC")
try:
zone = ZoneInfo(zone_name)
except ZoneInfoNotFoundError:
sys.exit(f"unknown time zone in REPORT_TZ: {zone_name!r}")
entries, other = parse_log(LOG_PATH)
lines = build_report(entries, other, zone)
out_dir = Path(os.environ.get("REPORT_DIR", "output"))
out_dir.mkdir(parents=True, exist_ok=True)
out_file = out_dir / "ops_report.txt"
out_file.write_text("\n".join(lines) + "\n", encoding="utf-8")
print("\n".join(lines))
print(f"\nReport written to {out_file.as_posix()}")
if __name__ == "__main__":
main()
Output
Operations report for 2024-05-01 (times in UTC)
===============================================
Log lines: 500 (8 traceback lines)
Levels: INFO 447, WARNING 25, DEBUG 13, ERROR 7
API requests: 391
Client errors (4xx): 51 (13.0%)
Server errors (5xx): 3 (0.8%)
Latency median / p95 / max: 40 / 221 / 1334 ms
Busiest endpoint: /api/v1/products (113 requests)
Users with 2+ rate-limited (429) requests: 5
a***@example.com 3
d***@example.net 2
l***@example.net 2
p***@example.com 2
t***@example.org 2
Pipeline runs: 9 started, 9 finished
Duration mean 5.72 s, longest run-0005 (11.55 s)
roc_auc min 0.812, max 0.844; 3 of 9 below 0.820
Errors:
10:37:08 [db] OperationalError: database is locked (attempt 1/3), retrying in 1s
10:53:55 [db] OperationalError: database is locked (attempt 1/3), retrying in 1s
10:53:56 [loader] Failed to parse data/reports/2024-04.csv
15:35:27 [loader] Failed to parse data/reports/2024-04.csv
17:18:02 [api] 198.51.100.23 POST /api/v1/predict 500 1188ms user=p***@example.com
18:28:00 [api] 203.0.113.45 GET /api/v1/products?page=2 500 1334ms user=p***@example.com
19:34:34 [api] 10.0.3.17 GET /api/v1/products?page=2 500 974ms user=t***@example.org
Report written to output/ops_report.txt

Run it with another time zone. The title and the error times change; the counts do not:

Terminal
REPORT_TZ=America/Chicago python ops_report.py > /dev/null
head -n 1 output/ops_report.txt
grep -A 3 "^Errors" output/ops_report.txt
Output
Operations report for 2024-05-01 (times in America/Chicago)
Errors:
05:37:08 [db] OperationalError: database is locked (attempt 1/3), retrying in 1s
05:53:55 [db] OperationalError: database is locked (attempt 1/3), retrying in 1s
05:53:56 [loader] Failed to parse data/reports/2024-04.csv

An invalid zone stops the script with a message on stderr and exit code 1:

Terminal
REPORT_TZ=Mars/Base python ops_report.py 2>&1
echo "exit code: $?"
Output
unknown time zone in REPORT_TZ: 'Mars/Base'
exit code: 1

How it works:

  1. Settings. os.environ.get() reads both settings with defaults. ZoneInfo() raises ZoneInfoNotFoundError for an unknown name, and sys.exit(message) turns that into a clear message and exit code 1.
  2. Parsing. LINE explains a whole line with four named groups; ^ and $ anchor it. A line that does not match is a traceback line and only counts. Each timestamp becomes an aware UTC datetime at once, so all later arithmetic is safe.
  3. API. REQUEST.fullmatch() accepts only messages that have exactly the API shape. status // 100 turns 404 into 4, so one Counter gives the 4xx and 5xx classes. quantiles(n=20) returns 19 cut points; the last one is the 95th percentile.
  4. Runs. defaultdict(dict) stores the start and finish time of each run under its id. The durations come from subtracting two aware datetimes, and total_seconds() turns them into floats for statistics.mean().
  5. Display. Times are converted with astimezone(zone) only when a line of the report is built. zone.key is the name of the zone, for the title.
  6. Privacy. mask() keeps the first letter and the domain of each email, both in the 429 list and in the error lines. The 429 list sorts on the full email before masking, so ties always come out in the same order.
  7. Output. as_posix() prints the relative path with forward slashes on every system.

Alternative: pandas can load the parsed entries into a DataFrame and compute the same numbers with groupby and quantile (module 25). For a 500-line log, the standard library is enough, and the script runs anywhere Python runs, with no installation.