---
title: "How to Track LLM API Token Usage in Python, by Day and Project"
description: "Log the usage field from each API response to a JSONL file, then sum tokens by day and project with a short script. Use two weeks of data to pick a plan."
url: https://cdnping.org/en/blog/track-ai-api-usage-yourself
language: en
published: 2026-11-08
category: "Developer tools"
tags: ["API usage","token tracking","logging","plan selection","Python"]
source: cdnping.org
license: Free to quote and summarize with a link to the url above.
---
# How to Track LLM API Token Usage in Python, by Day and Project

The most reliable way to track API usage is to append the `usage` field from each response to a log file, along with a timestamp, project name, and model name, then summarize by day. You don't need a database or a monitoring platform. A JSONL file and one short script are enough, and two weeks of logs will show you your daily average and your peaks.

Below: which fields to record, the logging code, the summary script, and how to use the results to pick a plan.

## Why not just read the billing dashboard?

The dashboard tells you the total you spent. It can't easily tell you which project costs the most, which day spiked, or whether input or output tokens drove the cost. The billing basis is also set by the provider, and you can't break it down to verify it. Keeping your own record gives you something to reconcile against. If a bill looks wrong, use your log to check it line by line; see [How to check when API billing looks wrong](/en/blog/relay-billing-token-mismatch).

## Which fields should you record per call?

Record just these. They're enough, and they don't touch the request body:

| Field | Source | Purpose |
| --- | --- | --- |
| ts | Local time | Summaries by day or hour |
| project | Passed in by you | Tell projects or tools apart |
| model | Model name in the request | Separate consumption by model |
| input_tokens | Response usage | Input-side usage |
| output_tokens | Response usage | Output-side usage |
| cache_tokens | Response usage (if present) | Cache reads/writes; follow the official docs for how they are counted |
| latency_ms | Local timer | Spot slowdowns along the way |
| status | HTTP status code | Count failures and retries |

The two common API formats use different field names. OpenAI-compatible responses usually have `usage.prompt_tokens` and `usage.completion_tokens`. Anthropic-style responses usually have `usage.input_tokens` and `usage.output_tokens`, with cache fields under other names. Check the official docs for the service you use; don't hard-code names from memory.

Don't write prompts or reply text to the log. The purpose of this log is counting, not archiving. Full text takes up space and creates a leak risk.

## How do you write the logging function?

Here is a small function that doesn't depend on any particular SDK. Pass it the usage you pulled from the response; it accepts both field-name formats:

```python
import json, time, pathlib

LOG = pathlib.Path("usage.jsonl")

def log_usage(project, model, usage, latency_ms, status=200):
    u = usage or {}
    row = {
        "ts": time.strftime("%Y-%m-%dT%H:%M:%S"),
        "project": project,
        "model": model,
        "input_tokens": u.get("prompt_tokens", u.get("input_tokens", 0)),
        "output_tokens": u.get("completion_tokens", u.get("output_tokens", 0)),
        "status": status,
        "latency_ms": latency_ms,
    }
    with LOG.open("a", encoding="utf-8") as f:
        f.write(json.dumps(row, ensure_ascii=False) + "\n")
```

At the call site it looks roughly like this:

```python
t0 = time.time()
resp = client.chat.completions.create(model=MODEL, messages=msgs)
log_usage("blog-tool", MODEL, resp.usage.model_dump(), int((time.time() - t0) * 1000))
```

A few things to watch for:

- With streaming, usage often appears only in the last chunk, or you may need to enable an option in the request. Check the official docs. If you can't get it, record 0 and flag the row; don't estimate from character counts.
- Log failed and timed-out requests too, with the real status code in `status`. Retries produce multiple calls, so you can see directly how much of your traffic is retries.
- If you use a ready-made tool such as Claude Code or Codex, you can't insert code into it. Check whether the tool has its own usage output, or look at your gateway's dashboard, then enter the numbers into the summary table below by hand.

## How do you summarize by day and by project?

Write a second script to read the log. The standard library is enough:

```python
import json, collections

by_day = collections.defaultdict(lambda: [0, 0, 0])   # input, output, number of calls
by_proj = collections.defaultdict(lambda: [0, 0, 0])

for line in open("usage.jsonl", encoding="utf-8"):
    r = json.loads(line)
    day = r["ts"][:10]
    for key, d in ((day, by_day), (r["project"], by_proj)):
        d[key][0] += r["input_tokens"]
        d[key][1] += r["output_tokens"]
        d[key][2] += 1

for k in sorted(by_day):
    i, o, n = by_day[k]
    print(f"{k}  in={i:>10,}  out={o:>9,}  calls={n}")
print()
for k, (i, o, n) in sorted(by_proj.items(), key=lambda x: -x[1][1]):
    print(f"{k:<16} in={i:>10,}  out={o:>9,}  calls={n}")
```

The output is a table of how much you used each day and which project used the most. It matters to look at input and output separately. Their per-token prices usually differ, and long-context workloads have large input volumes, so adding the two together hides the problem. For how billing is calculated, see [How token billing works](/en/blog/llm-token-billing-explained).

## What should you look at after two weeks?

Don't look only at the average. Fill in a small table like this:

| Metric | How to get it | Notes |
| --- | --- | --- |
| Average daily output tokens | Total output / number of days | Basis for estimating monthly usage |
| Peak-day output tokens | The largest single day | Your plan has to survive days like this |
| Failed-call share | Non-2xx status / total calls | If high, check retries and rate limits first |
| Share of the costliest project | Top project / total | Tells you where to optimize first |

You can estimate monthly usage as "daily average times 30, plus headroom for peak days." This is a rough method, not a precise forecast. If you're running a coding agent, the input-side context is counted over and over, so also read [How to estimate Claude Code token consumption](/en/blog/ai-coding-agent-token-cost-estimate) and [How to estimate your monthly token usage](/en/blog/estimate-monthly-token-usage). Those two cover estimating without logs; once you have logs, you can cross-check one against the other.

## How do you pick a plan once you have the data?

First convert your data into the unit of the plans you're comparing. Take AGI Plan as an example (AGI Plan is a commercial partner of cdnping). It is a monthly subscription billed in RMB, with no overseas credit card needed. Plans are Lite ¥49/month, Plus ¥119/month, Pro ¥649/month, and Max ¥1,368/month. The four tiers differ only in quota, and annual billing is 20% off. The metering unit is the CU: 1 CU equals 1,000 output tokens on the baseline model. You can also pay as you go at 1 yuan = 500 CU, with a ¥20 minimum top-up. The CU rate varies by capability group and by model, so check the [AGI Plan site](https://agiplan.dev/pricing) and the [models page](https://agiplan.dev/models) rather than guessing when you convert. Some models are marked "overseas only"; whether they are available to you also depends on the official site.

A simple order of decisions:

1. Take your monthly output volume from the log and convert it to CU using the rates on the site.
2. Look at the pay-as-you-go cost first, then at monthly plans. If you often hit the quota on peak days, pick a higher tier. If you never use the full quota in a month, pick a lower tier or pay as you go.
3. If overage is sporadic, don't upgrade just for the occasional peak.
4. To keep using Claude Code or Codex, you only need to change one endpoint URL. For the steps, see [Custom API endpoints for Claude Code, Codex, and OpenCode](/en/blog/configure-custom-api-endpoint-claude-code-codex).

If your quota runs out halfway through the period, see [Claude Code quota not enough](/en/blog/claude-code-quota-not-enough). Use the log to find the biggest consumers first, then decide whether to upgrade or switch billing method.

## What else is easy to miss?

- Reconcile your log against the provider's dashboard at least once. If your local total is clearly different from the dashboard, check three things first: streaming responses with no usage, retries, and cache fields.
- If several people share one key, include the person in the `project` field. Otherwise the summary can't be traced back to whoever is responsible.
- Service availability also affects usage: failed retries increase call counts and token consumption, and whether they are billed depends on the provider's rules. To check whether a service is stable right now, see [AGI Plan's status page](/en/status/agiplan), or use [cdnping's model monitoring](/en/models) to see availability across models.

## Next step

Add `log_usage` to the script you use most today, let it run for 14 days, then run the summary script. With three numbers in hand (daily average, peak, and failure share), compare against the tiers on the [AGI Plan pricing page](https://agiplan.dev/pricing). If you want to see the onboarding flow first, start at [agiplan.dev/startup](https://agiplan.dev/startup). Setup takes three steps: sign up with an email verification code, choose a plan and create a key, and change one setting.
