Skip to content

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:

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

Alerts worth setting

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

Next: How to read your token bill. If you route several providers and want one view of usage, see TokenCenter .

All field notes