---
title: "Write a log file and read it"
summary: "Make your API write one line per request to a log file, then follow it live with tail, search it with grep and count it with wc."
url: "https://lab.blue-unlimited.com/en/learn/write-a-log-file-and-read-it"
language: en
updated: "2026-10-25"
---

[Home](https://lab.blue-unlimited.com/en) / [Learn](https://lab.blue-unlimited.com/en/learn) / Write a log file and read it

**Guide · Python**

# Write a log file and read it

Make your API write one line per request to a log file, then follow it live with tail, search it with grep and count it with wc.

- **Reading time**: 7 min
- **Tested on**: 2026-10-25

Make your API write one line per request to a log file, then follow it live with tail, search it with grep and count it with wc.

## In plain words

A log is the diary of a program. Every time something happens it writes one line: when, what. When something goes wrong later, the diary tells you what happened while you were not looking.

## Try it yourself

Change the route in `app.py` so each request adds a line to `requests.log`. The new parts are the import and the three lines that open the file:

```python
from datetime import datetime, timezone

@app.get("/upper")
def upper():
    text = request.args.get("text", "")
    ts = datetime.now(timezone.utc).isoformat()
    with open("requests.log", "a", encoding="utf-8") as f:
        f.write(f"{ts}\t{text}\t{text.upper()}\n")
    return jsonify({"original": text, "upper": text.upper()})
```

Run the app, then in a second terminal send a few requests and read the log:

```bash
curl -s "http://localhost:8000/upper?text=one" > /dev/null
curl -s "http://localhost:8000/upper?text=two" > /dev/null
cat requests.log
tail -f requests.log     # live; Ctrl+C to stop
grep two requests.log
wc -l requests.log
```

## A step further

The `"a"` means **append**: add to the end. With `"w"` every run would erase the file, and a log you lose is no log. Times are in UTC so logs from different machines line up. `\t` (a tab) separates the columns so `cut -f2` can pick one.

Check who may write the file with `ls -l requests.log`. And think before you log: **never write passwords, keys or other people's private details into a log.**

## How it works in real projects

Logs are read by people and by tools, so each line is one event, with a time. They grow forever, so real systems **rotate** them (start a new file daily and keep a few old ones) and send them to a central place. When you ask a team member "what happened at 14:20?", the log is the answer.

## Tools in this guide

- [AI Workshops](https://lab.blue-unlimited.com/en/ai-workshops) (More time, Internal): AI agents and skills built around your processes and your voice, and your team trained to work with them safely.

## Not sure where to start? Tell us what's slowing you down. Let's chat.

[Let's chat](https://lab.blue-unlimited.com/en/contact?cta=chat&item=write-a-log-file-and-read-it)
