Log tokens per request
The vendor dashboard tells you what you spent. Your own log tells you why. Most chat APIs already return token counts with each response. Saving them takes a few lines.
What to record
For every model call:
- time
- feature (which part of your app made the call)
- model
- input tokens and output tokens
- cached tokens, if your provider reports them
- attempt number (1 for the first try)
- user or account ID, if you need per-customer views (mind your privacy rules)
- finish reason, to catch cut-off replies
Do not log the prompt text by default. It can hold private data and it makes logs huge. Log sizes, not contents.
A minimal logger
Field names differ between vendors, for example prompt_tokens versus input_tokens. Map them in one place:
import json, time
def log_usage(feature, model, usage, attempt=1, path="tokens.log"):
"""usage: the token counts your API returns with each response.
Field names differ by vendor; map them here once."""
row = {
"ts": time.strftime("%Y-%m-%dT%H:%M:%S"),
"feature": feature,
"model": model,
"input": usage.get("input_tokens", usage.get("prompt_tokens", 0)),
"output": usage.get("output_tokens", usage.get("completion_tokens", 0)),
"attempt": attempt,
}
with open(path, "a") as f:
f.write(json.dumps(row) + "\n")
return row
if __name__ == "__main__":
import os, tempfile
p = os.path.join(tempfile.mkdtemp(), "tokens.log")
log_usage("support-bot", "model-a", {"prompt_tokens": 1200, "completion_tokens": 300}, path=p)
log_usage("search", "model-b", {"input_tokens": 400, "output_tokens": 90}, path=p)
totals = {}
for line in open(p):
r = json.loads(line)
t = totals.setdefault(r["feature"], [0, 0])
t[0] += r["input"]; t[1] += r["output"]
print(totals)
One JSON line per call is enough to start. Later you can send the same rows to your metrics system.
Questions your log can now answer
- Which feature uses the most input tokens?
- Did tokens per call go up after last week's prompt change?
- How many calls are retries?
- Which users or accounts cost the most?
- Is the cache being used?
Alerts worth setting
- Average input tokens per call up sharply day over day.
- Attempts per request above your normal level.
- Any call using a model you did not expect.
- Output tokens hitting your cap often (answers being cut off).
Keep it cheap
Logging should never slow down or break the call. Write asynchronously or buffer, and if the logger fails, drop the row and keep going.
Checklist
- Log counts, model, feature, attempt and finish reason.
- Map vendor field names in one place.
- Do not log prompt text by default.
- Set two or three simple alerts.
- Review the top features weekly.
Next: How to read your token bill. If you route several providers and want one view of usage, see TokenCenter .