Sub topic 5
Logging model, tokens, latency, and status
This chapter assumes you can call an LLM API from Python, know application log levels, and have read the earlier chapters on the metadata-first policy and structured JSON logs. Here you decide which metadata fields to record for each call and how to capture them reliably, including on failure.
Why metadata is the useful part
Most questions you ask of LLM logs do not need the text. You want to know what a feature costs, why it got slow, and how often calls fail. Four kinds of field answer those questions, and none of them contains user content.
| Field | Example | Answers |
|---|---|---|
| `model` | `"small-v2"` | Which model produced a cost or latency change? |
| `input_tokens`, `output_tokens` | `812`, `164` | What does this call cost? Is a prompt growing? |
| `latency_ms` | `1830` | Is the provider slow, or is our code slow? |
| `status`, `error_type` | `"timeout"` | What fails, and how often? |
Add finish_reason (for example stop or length). It shows when output was cut off at the token limit, which looks like a success in the status field.
Where each value comes from
- Model: log the model name you requested. If the response reports the model that actually served the call, log that too, because aliases such as "latest" can change underneath you.
- Tokens: read the usage numbers from the provider's response. Counting tokens yourself is only an estimate. Log
prompt_charsas a fallback for failed calls, which return no usage. - Latency: use
time.perf_counter(), which is monotonic.time.time()can jump when the system clock adjusts. - Status: use a small fixed set of values, such as
ok,timeout,rate_limitedanderror. A fixed set makes counting and alerting simple.
A wrapper that records all four
The key design choice is a finally block. It writes exactly one record whether the call succeeds or raises, so failures are never missing from the logs.
import json
import logging
import time
import uuid
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger("llm")
def call_with_metadata(client_call, model: str, prompt: str) -> dict:
record = {
"event": "llm_call",
"request_id": str(uuid.uuid4()),
"model": model,
"prompt_chars": len(prompt),
"status": "error",
}
start = time.perf_counter()
try:
result = client_call(model=model, prompt=prompt)
usage = result.get("usage", {})
record["status"] = "ok"
record["input_tokens"] = usage.get("input_tokens")
record["output_tokens"] = usage.get("output_tokens")
record["finish_reason"] = result.get("finish_reason")
return result
except TimeoutError:
record["status"] = "timeout"
raise
except Exception as exc:
record["error_type"] = type(exc).__name__
raise
finally:
record["latency_ms"] = round((time.perf_counter() - start) * 1000)
logger.info(json.dumps(record))
def fake_client(model, prompt):
return {
"text": "Hello!",
"usage": {"input_tokens": 12, "output_tokens": 3},
"finish_reason": "stop",
}
call_with_metadata(fake_client, "small-v2", "Say hello")The status field starts as "error", so any path you forgot to handle is still reported as a failure instead of looking like a success.
Common errors
- Logging only on success. Failed and timed-out calls are the ones you most need to see.
- Logging
str(exc). Some provider errors echo part of the request, which can include prompt text. Log the exception type and an HTTP status code instead. - Averaging latency. Averages hide slow calls. Record raw
latency_msand compute percentiles such as p95 in your log tooling. - Free-form status strings.
"failed","Failed"and"error"split one count into three.
Exercise
A call hits the token limit and returns a truncated answer with no exception. The wrapper above logs status: "ok". Which field lets you detect the truncation, and what value would you alert on?
Show answer
The finish_reason field. A value such as length (the exact name depends on the provider) means the output stopped at the token limit. Alert when its share of calls rises, or log a distinct status for it.