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.
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:
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:
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.