Course contents · Lesson 14 of 16

Observe Your LLM App: Logs, Traces and Token Usage

Quality, Cost and Safety · Lesson 14 of 16 · 12 min Hands-on

A colleague sends you a screenshot: yesterday afternoon the handbook assistant took twelve seconds and gave a muddled answer about leave. You ask the same question now, and it answers well in seven. Without a record of yesterday's request, all you can do is guess. This lesson shows how to observe your LLM app: one structured log line per request, timed steps called spans, and token counts you can add up per day.

The black box: one JSON line per request

Real users bring two questions: "why did it say that?" and "why was it slow yesterday?" Both need facts about one past request, written down when it happened, and a print() vanishes with your terminal window.

A structured log records each event as named fields instead of a sentence, so code can filter and add them up (see Structured Logging). The lab appends one JSON object per request to logs/app.jsonl, the JSONL format of lesson 11: one complete object per line. Each line holds:

  • A request id: a random id of 32 hex characters, new for every request, so you can find that request again.
  • The model and a prompt version: prompt_version is a label you change whenever you edit the system rule, so answers before and after can be compared.
  • The retrieved chunk ids: such as 03-leave.md#89, the file and start position from the index of lesson 9, not the text.
  • Token counts: Ollama's prompt_eval_count and eval_count (lesson 2), logged as prompt_tokens and completion_tokens, the names OpenAI-compatible APIs use.
  • Latency and outcome: the whole time in milliseconds, and answered, refused (the model said "I do not know") or error. Failed requests get a line too.
One log line from logs/app.jsonl, split over lines for reading, with illustrative values: ts, request_id, model llama3.2:3b, prompt_version rag-v1, question_chars 25, top_k 4, chunks 03-leave.md#0 and 03-leave.md#89 and more, best_score 0.712, prompt_tokens 431, completion_tokens 62, load_ms 38.2, outcome answered, answer_chars 236, spans for retrieve, 41.3 ms, and generate, 6843.0 ms, and latency_ms 6890.4. Callouts: request_id finds this one request again; model and prompt_version say what answered with which prompt; question_chars and answer_chars are sizes, not text; chunks say which passages it read, by id; the token counts are the cost meter; load_ms in the thousands means the model was loading; outcome is answered, refused or error; spans and latency_ms show where the time went.
Every field answers a question someone will ask later, and none of them is the question's text.

In the flowchart, each step adds its fields, and the line is written once, when the request ends, so every request is one whole line.

Flowchart of one request: 1, request, the question comes in; 2, retrieve, a span of 41 ms; 3, build prompt, the rule plus the chunks; 4, generate, a span of 6.84 s; 5, response, the answer goes out. Under each step, the fields it adds: request_id, ts, model and question_chars; chunks, best_score and the retrieve span; prompt_version, not timed because it takes microseconds; prompt_tokens, completion_tokens, load_ms and the generate span; outcome, answer_chars and latency_ms. All of them feed one line in logs/app.jsonl, appended once at the end, which summarize_logs.py reads for requests, latency and tokens per day. Times are illustrative.
Every step adds fields, but only retrieve and generate are worth timing.

Spans: time each step of a request

A span is one timed step of a request: a name, when it started and how long it took. All the spans of one request, tied together by its id, make a trace. What Is Distributed Tracing? follows traces across many services; here everything runs in one Python process, so a span is simple bookkeeping.

observe.py does it with a context manager, code that runs before and after a with block; @contextmanager builds one from a function. Simplified, with its use in traced_ask.py below it:

@contextmanager
def span(self, name):
    start = time.perf_counter()
    try:
        yield                     # the code inside the with block runs here
    finally:                      # runs even if that code fails
        self.spans.append({"name": name,
                           "start_ms": round((start - self.started) * 1000, 1),
                           "duration_ms": round((time.perf_counter() - start) * 1000, 1)})

with trace.span("retrieve"):
    retrieved = retrieve(question, index, args.top_k)
messages = build_messages(question, retrieved)   # microseconds: not worth a span
with trace.span("generate"):
    reply = chat(messages, args.model)

time.perf_counter() is the interval clock of lesson 12. Because of finally, a step that fails still leaves its span, so an error line shows how far the request got.

Drawn on one time axis, spans make a waterfall: one bar per span, starting where it started. Here are a normal request and yesterday's slow one:

Waterfall of two requests on a time axis from 0 to 14 seconds, illustrative numbers. Today at 10:15, models already loaded: ask lasts 6.89 s; retrieve is a sliver of 41 ms at the start; generate takes 6.84 s for 431 tokens in and 62 out. Yesterday at 16:02, after a quiet hour: ask lasts 11.84 s; retrieve takes 1.52 s because the embedding model was loading first; generate takes 10.31 s, of which load_ms is 3,460 and 6.85 s is real work. Footer: look at the longest bar first; a large load_ms means a model was loading.
Retrieval is a sliver; generation, and loading the models, is where the time goes.

The aha is how thin retrieve is: speed work starts with the prompt and the model, not the search. In the slow one, after a quiet hour both models had been unloaded, so retrieve waited for the embedding model and load_ms shows the chat model loading.

Run it and count tokens per day

The lab is course-labs/building-llm-apps/14-observability. With Ollama on port 11434 and both llama3.2:3b and nomic-embed-text pulled, run:

cd course-labs/building-llm-apps/14-observability
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
python3 index.py data/handbook
python3 traced_ask.py 'What is the leave policy?'

index.py should report the same 34 chunks as in lessons 9 to 12. Then traced_ask.py prints the request id, the chunk ids, the answer and a text waterfall of its spans. Trimmed, with illustrative values:

Request id: 7c2f9a41d3e84b0f9a6e51c2d8b7f034
Retrieved: 03-leave.md#0, 03-leave.md#89, 03-leave.md#1030, 03-leave.md#746
...
Tokens: 431 in, 62 out. Outcome: answered.

Spans, 6.89 s in all (one # is 0.17 s):
  retrieve  starts  0.00 s  takes  0.04 s  |#
  generate  starts  0.04 s  takes  6.84 s  |########################################

Appended 1 line to logs/app.jsonl

It worked if tail -n 1 logs/app.jsonl prints the new line. If Ollama is stopped, you see cannot connect to Ollama, and a line is still logged, with "outcome": "error".

A metric is a number measured over time (What Is a Metric?). Tokens per request and per day are your cost metric: hosted APIs bill per token (lesson 12). A runaway prompt, such as a bug that resends every chunk or the whole chat history, multiplies tokens before anyone sees the bill. --top-k 34 imitates that bug:

python3 traced_ask.py 'What is the leave policy?' --top-k 34
python3 summarize_logs.py
...
tokens in             2,544
tokens out            118
tokens per request    1,331

Tokens per day (UTC), budget 100,000:
  2026-12-03     2 requests      2,662 tokens    2.7%

Requests over 1,500 prompt tokens: 1
  2026-12-03T10:21:07  4b8e0d5f9c2a4e7b8d1f6a3c5e9b2d70  prompt_tokens 2,113  top_k 34  rag-v1

The summary, trimmed and illustrative, also shows outcomes, latency and span averages. It worked if the runaway request is listed with about five times the usual tokens in. With --daily-budget 2000 the day is marked over budget; in production, both checks would raise alerts.

Optional: the same spans in Jaeger

OpenTelemetry (OTel) is the open standard for sending traces, metrics and logs (What Is OpenTelemetry?), and Jaeger is an open-source trace viewer. With --otel, every span() also opens an OTel span under a root span named ask, and the SDK sends them as OTLP, OpenTelemetry's protocol, to port 4318. The lab's docker-compose.yml runs Jaeger 2.23.0 on 127.0.0.1:

docker compose up -d
pip install -r requirements-otel.txt
python3 traced_ask.py 'What is the leave policy?' --otel

Open http://localhost:16686, pick Service handbook-assistant and click Find Traces: you should see an ask trace with 3 spans, whose trace id is the line's request_id. The generate span carries gen_ai.usage.input_tokens and gen_ai.usage.output_tokens, from the OpenTelemetry GenAI conventions, still marked Development. None of this is required: the JSON line already answers both questions.

Privacy: log sizes and ids, not secrets

A log is a second copy of your users' data, often kept longer and read by more people than the app. Never log secrets such as API keys, passwords or access tokens. Treat questions as personal data too: "I am off sick with a back injury, what do I get?" holds a health detail.

So the lab logs sizes and ids: question_chars, answer_chars and chunk ids. While the documents stay unchanged, the chunk ids and prompt_version rebuild everything in the prompt except the question. --log-text adds the question and answer, only where your policy allows it; the GenAI conventions likewise make message content opt-in. Decide also how long logs are kept (Log Aggregation and Retention).

Check yourself

Yesterday's parental leave answer was wrong, and its log line has chunk ids but no text. Was retrieval or generation at fault?

Read chunks. If no Parental leave chunk of 03-leave.md is listed, retrieval failed; if it is, the model misread it. The ids point to the exact text, so no copy is needed.

Average latency is 6 seconds, yet some users wait 12. Which fields of the slow lines tell you why?

The spans and load_ms. A long generate with load_ms in the thousands means a cold model; a long retrieve points at the embedding call. An average hides a few slow requests.

A teammate wants to log every full prompt "just in case". What is the risk, and what gives most of the benefit?

Questions can hold personal data, and logs outlive the request and reach more readers. Chunk ids, prompt_version and sizes explain most requests without storing anyone's words.

Go deeper