Sub topic 5
Logging model, tokens, latency, and status
This chapter covers the metadata record you write for every LLM call. It assumes you can call an LLM API from Python, know how application log levels work, and have used basic regular expressions. The metadata record is the safest and most useful thing you can log, so it is the default in the policy from the previous chapters: metadata always, content only by exception.
Why metadata comes first
Metadata is information about a call, not the call's text. It answers the questions you ask most often in production:
- Which model handled this request?
- How many tokens did it use, and so what did it cost?
- How long did it take?
- Did it succeed, and if not, why?
None of these answers needs the prompt or the response. A log made only of metadata can still drive dashboards, cost reports, latency alerts, and error-rate alerts. It also carries much less risk than a log of user text.
Metadata is not automatically safe. A free-form error message, a user ID, or a prompt hash can all identify someone or leak information. The sections below mark where that happens.
The fields to record
A useful baseline record has these fields.
| Field | Type | Why you want it |
|---|---|---|
| `event` | string | A fixed name such as `llm_call`, so you can filter on it |
| `request_id` | string | Ties this record to others (the next chapter covers correlation) |
| `model` | string | Cost and quality differ by model |
| `prompt_chars` | integer | A cheap size measure that needs no tokenizer |
| `prompt_sha256` | string | Lets you spot repeated prompts without storing them |
| `status` | `ok` or `error` | The basis of every error-rate chart |
| `error_type` | string | The exception class name, not the message |
| `response_chars` | integer | Detects empty or runaway responses |
| `latency_ms` | integer | The basis of latency percentiles |
| `input_tokens`, `output_tokens` | integer | The basis of cost tracking |
Characters and tokens are different units. A token is a chunk of text the model reads or writes, often a short word or part of a word. Providers bill by tokens, so character counts are only a rough stand-in. Use the token counts the provider returns whenever you can.
The wrapper
The wrapper below logs only metadata by default. It adds redacted, truncated content only when log_content is true. It relies on the redact function from the redaction chapter, which is repeated here so the example runs on its own.
import hashlib
import json
import logging
import re
import time
import uuid
logger = logging.getLogger("llm")
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
API_KEY = re.compile(r"\b(?:sk|key|token)[-_][A-Za-z0-9_-]{16,}\b")
def redact(text: str) -> str:
text = EMAIL.sub("[EMAIL]", text)
text = API_KEY.sub("[SECRET]", text)
return text
def call_logged(client_call, model: str, prompt: str, log_content: bool = False) -> str:
record = {
"event": "llm_call",
"request_id": str(uuid.uuid4()),
"model": model,
"prompt_chars": len(prompt),
"prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
}
start = time.perf_counter()
try:
response = client_call(model=model, prompt=prompt)
record["status"] = "ok"
record["response_chars"] = len(response)
if log_content:
record["prompt"] = redact(prompt)[:2000]
record["response"] = redact(response)[:2000]
return response
except Exception as exc:
record["status"] = "error"
record["error_type"] = type(exc).__name__
raise
finally:
record["latency_ms"] = round((time.perf_counter() - start) * 1000)
logger.info(json.dumps(record))Three design choices in this wrapper are worth understanding.
- One record per call. The
finallyblock runs on success and on failure, so every call produces exactly one line. You never have to join a "started" line to a "finished" line. - The error is re-raised. The wrapper logs the failure and then lets the exception continue. Logging must not change the program's behavior.
json.dumpsbuilds the line. It escapes newlines inside strings, so text from the model cannot start a fake log line. A later chapter treats this attack in detail.
Running it
You can test the wrapper without a real API by passing a fake client function.
import logging
logging.basicConfig(level=logging.INFO, format="%(message)s")
def fake_client(model: str, prompt: str) -> str:
return "Hello from " + model
call_logged(fake_client, "demo-model", "Say hello to [email protected]")The output is one JSON line. The request_id and the latency_ms value will differ on your machine.
# {"event": "llm_call", "request_id": "...", "model": "demo-model",
# "prompt_chars": 28, "prompt_sha256": "...", "status": "ok",
# "response_chars": 21, "latency_ms": 0}The email address does not appear anywhere in the line, because log_content defaults to false.
Measuring latency correctly
The wrapper uses time.perf_counter() and not time.time(). The wall clock can jump when the system adjusts the time, which can produce negative or inflated durations. perf_counter() is a monotonic clock, meaning it only moves forward, so differences between two readings are reliable.
Some points about what the number means:
- The timer starts before the client call and stops in
finally. It therefore includes network time, provider queueing, generation time, and any retries your client performs internally. - If your client retries on failure, the logged latency is the total across attempts. Log the attempt count as a separate field if your client exposes it, so a slow call and a retried call can be told apart.
- Report latency as percentiles (p50, p95, p99), not averages. LLM latency has a long tail, and an average hides the slow calls users notice.
- For streamed responses, total latency is less useful than time to first token. The streaming chapter covers this.
Recording token counts
Most provider responses include a usage object with input and output token counts. The exact field names vary by provider, so read the documentation for yours. A common shape looks like this.
def usage_fields(usage: dict | None) -> dict:
"""Pick token counts out of a provider usage object, if present."""
if not usage:
return {}
return {
"input_tokens": usage.get("input_tokens"),
"output_tokens": usage.get("output_tokens"),
}Merge the result into the record with record.update(usage_fields(usage)). Our simple wrapper returns a string and so cannot see the usage object. In a real client, return the full response object from the inner call, log from it, and then return the text.
Edge cases to handle:
- Missing usage. Some providers omit usage on errors or on streamed calls. Log
None(JSONnull) and not zero. A zero would look like a free call and distort cost reports. - Counting yourself. If you estimate tokens with a local tokenizer, name the field differently, such as
input_tokens_est. Mixing estimates and provider-reported counts in one field makes totals unreliable. - Cached and reasoning tokens. Some providers report cached input tokens or hidden reasoning tokens separately, and bill them differently. Record them as their own fields if they affect your bill.
- Cost. Store token counts, not computed dollar cost. Prices change, and you can recompute cost later from the counts and a price table.
Recording status and errors
Status has two layers. The wrapper above records only the coarse layer, ok or error. In practice you want a bit more.
- HTTP or API status code, when the client exposes one. A
429(rate limited) needs a different response than a500(server error) or a400(bad request). - Finish reason, which tells you why generation stopped. Values such as
length(hit the token limit) indicate truncated answers that a plainokhides. - Error type, taken from the exception class name.
Log type(exc).__name__ and not str(exc). Error messages from client libraries sometimes echo the request, including parts of the prompt or the Authorization header. The class name is a fixed string you control. If you need the message for debugging, pass it through redact and truncate it, and treat it as content under the gated policy.
Metadata that can still identify people
A few metadata fields carry risk:
- The prompt hash. A SHA-256 hash of a short or predictable prompt can be reversed by guessing. Someone with log access can hash likely prompts and compare. For prompts that might be short or guessable, use a keyed hash (HMAC) with a secret key, or skip the hash. The hashing chapter covers this.
- User and tenant IDs. Log them only if you need per-user cost or debugging, and prefer an internal ID over an email address.
- Prompt size. An unusual
prompt_charsvalue can reveal something about content, but this is a minor risk compared with storing the text.
Common mistakes
- Logging only on success. Failed calls are the ones you most need to see. Keep the logging in
finally. - Using
time.time()for durations. The clock can move backward. - Recording zero for missing tokens. Use
nullso reports can tell "unknown" from "none". - Logging exception messages. They can contain user text or credentials.
- Letting the logger raise. If serialization fails, for example on a value
json.dumpscannot handle, the exception hides the real result of the call. Keep the record to plain types, or wrap the logging call so a logging failure never breaks the request. - High-cardinality fields in metrics. Fields such as
request_idbelong in logs. If you also turn fields into metric labels, use only low-cardinality ones such asmodelandstatus.
Summary of the working model
Every LLM call yields exactly one structured record. The record holds the model name, sizes, token counts from the provider, a monotonic latency measurement, and a status with an error type. Content stays out unless a gate allows it, and then only after redaction and truncation. With this record alone you can answer questions about cost, speed, and reliability without holding anyone's text.
Exercise
A teammate changes the wrapper so that the except block adds record["error"] = str(exc). Give two reasons this conflicts with the metadata-first policy, and name the field the wrapper uses instead.
Show answer
First, the exception message can contain parts of the prompt, the user's text, or request headers such as the API key, because some client libraries echo the request in errors. That puts sensitive content into a record that is supposed to hold metadata only. Second, the message is free-form and unbounded, so it can be very long and can differ on every call, which makes it hard to group and count. The wrapper uses error_type, set to type(exc).__name__, which is a short fixed string. If the message is needed for debugging, redact and truncate it and log it only under the gated content policy.
Exercise
A provider omits the usage object on streamed calls. Should you log input_tokens as 0 for those calls? Explain what to do instead and why.
Show answer
No. Log null (Python None). A value of 0 would be read as "this call used no tokens" and would lower cost totals and averages. Using null marks the value as unknown, so reports can exclude those calls or count them separately. If you estimate the count with a local tokenizer, store it in a separate field such as input_tokens_est so estimates never mix with provider-reported numbers.