# Write a run log: one line per crawl in runs/log.txt | Spider

Have the crawl script append a line to runs/log.txt after each run: start time, pages asked for, rows written, seconds and the exit code.

Canonical: https://spider.cloud/learn/course/write-a-run-log/

A run log is a text file the script opens in append mode as each run ends, adding one line: start time, pages asked for, rows written, seconds and exit code. Append mode leaves earlier lines alone, so each run adds its line below the others, failed runs included.

You finish with `runs/log.txt` holding three lines, one of them from a run you broke on purpose, and a `run_log.py` you have edited to write all five of those fields.

## A folder with no summary

[Lesson 10](/learn/course/keep-every-run/) left you with `keep_runs.py`, which crawls up to 20 pages and writes each run to its own CSV file named after its start time in UTC. The folder holds every run's rows. What it lacks is a summary. To learn whether last night's run worked, you have to open its file and count, and a run that stopped before writing anything leaves no file to open.

## Append, not write

Lesson 10's recorded script opened run files with `"w"`, which empties a file before writing to it, and you changed yours to `"x"`, which refuses a name that already exists. A log needs a third mode. Python's documentation for `open()` gives the `'a'` mode as "open for writing, appending to the end of file if it exists". The first run creates `runs/log.txt`, and every run after it adds a line below the ones already there.

The same page adds that on some Unix systems append mode means "all writes append to the end of the file regardless of the current seek position". This script never moves the position, so on any system its line goes to the end.

## What run_log.py adds

`run_log.py` is `keep_runs.py` with a first version of the log. Its line holds the start time, the start address, the pages that came back, how many answered 200, and ok or failed. The pages asked for, rows written, seconds and exit code come in an edit after the runs. These are the lines that changed from lesson 10:

- A `LOG` constant names the file, and a small `log()` function opens it with `"a"` and writes one line.
- `os.makedirs("runs", exist_ok=True)` moves up to just after the key check, so the folder exists before anything can go wrong.
- The early `nothing came back` exit is gone. The script counts the pages that answered 200 into `good`, writes the CSV only when at least one page came back, and sets the verdict to `ok` only when every page answered 200.
- Once the API has answered, it calls `log()` whatever the verdict, then prints the verdict and every line of the log.

The verdict and the exit code agree. The script returns 0 when the verdict is `ok` and 1 when it is `failed`, so the last word on each log line tells you how the run exited. Python's documentation for `sys.exit` says zero counts as successful termination and "any nonzero value is considered … abnormal termination" by shells. A scheduler reads that number, and you read the word.

The script reads your key from the `SPIDER_API_KEY` environment variable, as in lesson 1. This is the script as it ran on 2026-11-20, under Python 3.14.7:

```python
"""Crawl a site through the Spider API, at most 20 pages, save the run to its own CSV file,
and add one line about the run to runs/log.txt.

    python3 run_log.py URL

Each log line holds the start time, the start address, the page count, how many pages
answered 200, and ok or failed. A failed run still gets its line.
Exit 0: every page answered 200.
Exit 1: the key is missing, nothing came back, or a page answered something else.
"""
import csv
import json
import os
import sys
import urllib.request
from datetime import datetime, timezone

API = "https://api.spider.cloud/crawl"
LOG = os.path.join("runs", "log.txt")


def log(started, url, pages, good, verdict):
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(f"{started:%Y-%m-%dT%H:%M:%SZ}  {url}  pages={pages}  ok={good}  {verdict}\n")


def main() -> int:
    if len(sys.argv) != 2:
        print("usage: python3 run_log.py URL")
        return 1
    url = sys.argv[1]
    key = os.environ.get("SPIDER_API_KEY")
    if not key:
        print("set SPIDER_API_KEY first, as in lesson 1")
        return 1

    os.makedirs("runs", exist_ok=True)
    started = datetime.now(timezone.utc)
    params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown"}
    req = urllib.request.Request(API, data=json.dumps(params).encode(), headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=300) as resp:
        pages = json.load(resp)
    if isinstance(pages, dict):
        pages = [pages]

    rows = sorted(((p.get("url") or "", p.get("status"), len((p.get("content") or "").encode()))
                   for p in pages))
    good = sum(1 for _, status, _ in rows if status == 200)
    if rows:
        out = os.path.join("runs", started.strftime("quotes-%Y-%m-%dT%H%M%SZ.csv"))
        with open(out, "w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(["url", "status", "bytes"])
            writer.writerows(rows)
    verdict = "ok" if rows and good == len(rows) else "failed"
    log(started, url, len(rows), good, verdict)
    print(f"{verdict}: {good} of {len(rows)} pages answered 200")
    with open(LOG, encoding="utf-8") as f:
        print("log:")
        for line in f.read().splitlines():
            print(f"  | {line}")
    return 0 if verdict == "ok" else 1


if __name__ == "__main__":
    sys.exit(main())
```

The recorded script still opens its CSV with `"w"`, and the edit later in this lesson puts your `"x"` back. As recorded, it also sends neither `user_agent` nor `delay`. Your copy should send both, with your own bot name and contact address in place of the example:

```python
    params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown",
              "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)", "delay": 1000}
```

## Three runs, one of them broken

Run it on the practice site, then on an address with a typo in it, then on the practice site again. Print the exit code after each one:

```bash
python3 run_log.py https://quotes.toscrape.com/
echo $?
python3 run_log.py https://quotes.toscrape.com/qoutes/
echo $?
python3 run_log.py https://quotes.toscrape.com/
echo $?
```

These are the three runs from 2026-11-20, a few seconds apart. The first took 5.5 seconds, exited 0 and printed this:

```text
ok: 20 of 20 pages answered 200
log:
  | 2026-11-20T22:34:34Z  https://quotes.toscrape.com/  pages=20  ok=20  ok
```

The second asked for `/qoutes/`, the misspelled path. It took 3.2 seconds and exited 1:

```text
failed: 0 of 1 pages answered 200
log:
  | 2026-11-20T22:34:34Z  https://quotes.toscrape.com/  pages=20  ok=20  ok
  | 2026-11-20T22:34:41Z  https://quotes.toscrape.com/qoutes/  pages=1  ok=0  failed
```

The third took 11.5 seconds, exited 0, and printed the whole log:

```text
ok: 20 of 20 pages answered 200
log:
  | 2026-11-20T22:34:34Z  https://quotes.toscrape.com/  pages=20  ok=20  ok
  | 2026-11-20T22:34:41Z  https://quotes.toscrape.com/qoutes/  pages=1  ok=0  failed
  | 2026-11-20T22:34:44Z  https://quotes.toscrape.com/  pages=20  ok=20  ok
```

## Read the log

Each run printed the lines before it unchanged, with its own line added at the bottom. That is append mode at work. The first line was still there after the failed run, and after the run that followed it.

The broken run is the one worth a look. One page came back, and it did not answer 200. The log says so in one line, `pages=1 ok=0 failed`, next to the start address that caused it. You can see the typo without opening a CSV file. Because a page did come back, the script also wrote a one-row CSV for that run, and the log line is how you know to ignore it.

The two good runs both logged `pages=20 ok=20`. Twenty is the `limit` the script sends, so the log cannot tell you whether the site had more pages to give. [Lesson 8 on depth](/learn/course/set-the-depth/) covers how far a crawl goes. The timings, 5.5 and 11.5 seconds, come from the run records and are not in the log. The recorded script does not time itself, and it never writes down the number it asked for, how many rows went into the CSV, or its exit code. The next section adds those.

## Log the rest of the run

The recorded version logs nothing when the key is missing or the request fails, and its line leaves out four of the five fields. Your edit fixes both. Add `import time` beside the other imports, and give `log()` the fields the recorded line left out:

```python
def log(started, url, asked, written, good, seconds, code):
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(f"{started:%Y-%m-%dT%H:%M:%SZ}  {url}  asked={asked}  rows={written}"
                f"  ok={good}  seconds={seconds:.1f}  exit={code}\n")
```

Then replace `main()` with this version. It keeps your `user_agent` and `delay`, opens the CSV with the `"x"` mode from lesson 10, and puts the work inside `try` with the log call in `finally`:

```python
def main() -> int:
    if len(sys.argv) != 2:
        print("usage: python3 run_log.py URL")
        return 1
    url = sys.argv[1]
    os.makedirs("runs", exist_ok=True)
    started = datetime.now(timezone.utc)
    t0 = time.monotonic()
    params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown",
              "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)", "delay": 1000}
    written, good, code = 0, 0, 1
    try:
        key = os.environ.get("SPIDER_API_KEY")
        if not key:
            print("set SPIDER_API_KEY first, as in lesson 1")
            return code
        req = urllib.request.Request(API, data=json.dumps(params).encode(), headers={
            "Authorization": f"Bearer {key}",
            "Content-Type": "application/json",
        })
        with urllib.request.urlopen(req, timeout=300) as resp:
            pages = json.load(resp)
        if isinstance(pages, dict):
            pages = [pages]
        rows = sorted(((p.get("url") or "", p.get("status"), len((p.get("content") or "").encode()))
                       for p in pages))
        good = sum(1 for _, status, _ in rows if status == 200)
        if rows:
            out = os.path.join("runs", started.strftime("quotes-%Y-%m-%dT%H%M%SZ.csv"))
            with open(out, "x", newline="", encoding="utf-8") as f:
                writer = csv.writer(f)
                writer.writerow(["url", "status", "bytes"])
                writer.writerows(rows)
            written = len(rows)
        code = 0 if rows and good == len(rows) else 1
        print(f"{'ok' if code == 0 else 'failed'}: {good} of {len(rows)} pages answered 200")
        return code
    finally:
        log(started, url, params["limit"], written, good, time.monotonic() - t0, code)
```

Python runs a `finally` block whether the `try` block returns or raises. A missing key, a request error, a reply that is not JSON and a CSV that cannot be written all end there, and each one logs `exit=1` before the script stops. `code` starts at 1 and becomes 0 only on the last line of a clean run, so a run that never gets that far is logged as a failure. An uncaught error still prints its traceback, and Python exits with 1, the same number the line holds.

`asked` reads the `limit` straight from `params`, so the log keeps up when you change it. `rows` counts data rows and leaves the header out, and it stays 0 when no file was written. `seconds` is measured from just after the start time is read until the log call, so it leaves out the time Python takes to start. The edit also drops the printout of the whole log, so read it with `tail`.

Run the edited script once on the practice site and read the end of the log:

```bash
python3 run_log.py https://quotes.toscrape.com/
echo $?
tail -n 2 runs/log.txt
```

The last line has the new shape and ends in `exit=0`, matching what `echo $?` printed. The line above it is still in the old shape, because append mode never rewrites a line that is already there.

## Where the log goes quiet

The recorded version said a failed run still gets its line, and that held only for a run the API answered. A missing key returned before `log()`, and a request error or a failed CSV write ended in a traceback with the log unchanged. Your edited version logs all of those. It still writes nothing when you leave out the address, because it returns before the clock starts, or when `runs/log.txt` itself cannot be written. In that case the terminal or your scheduler's output has the reason.

## Try it yourself

In the edited script, change `"limit": 20` to `"limit": 5`, keeping the `user_agent` and `delay`. Run it once on the practice site:

```bash
python3 run_log.py https://quotes.toscrape.com/
echo $?
tail -n 1 runs/log.txt
```

You are done when `echo $?` prints 0 and the last line of `runs/log.txt` reads `asked=5`, has a `rows=` figure no larger than 5, and ends in `exit=0`.

## Do this, avoid this

The log is also a record of how often you crawl each site, since each line marks one crawl and when it started. It says nothing about the gap between single requests inside a crawl, which is what `delay` sets. [Lesson 4](/learn/course/pace-your-requests/) covers how fast is polite, and the site's terms decide whether a scheduled job is welcome at all.

### Do this

- Open the log file with a, so each run adds a line and the older lines stay.
- Write the log line after the counts are known, on the failed path as well as the passing one.
- Write the exit code into the line from the same variable the script returns, so the file and the shell agree.
- Log counts, not page text. Before you log the addresses of your own jobs, drop any part of a path or query that names a person or carries a token.

### Avoid this

- Opening the log with w, which empties every earlier line on the next run.
- Putting a return or an error path outside the try block that ends in the log call.
- Reading a missing line as a passing run. Check the exit code and the terminal output.

## Next

Each run, good or bad, now leaves a dated line in `runs/log.txt`, and the [web scraping](/web-scraping/) job has a history you can read in one screen. The script still runs to the end after a bad start, though. The next lesson asks how to make it stop the moment a run goes wrong, before it writes files you will have to throw away.

## Sources

1. [Python documentation, Built-in functions, open()](https://docs.python.org/3/library/functions.html) Read November 21, 2026
2. [Python documentation, sys: System-specific parameters and functions, sys.exit](https://docs.python.org/3/library/sys.html) Read November 21, 2026
