Sub topic 1
Why you log LLM requests and what can go wrong
Prerequisites
This chapter assumes you have:
- Basic Python, enough to read short functions and use the
loggingmodule. - Experience calling an LLM API, so you know what a prompt, a response, and a request header are.
- Familiarity with application logs and log levels such as INFO and ERROR.
- Basic regular expressions, which later chapters use for redaction.
You don't need security experience. This chapter explains the reasons for logging LLM traffic and the ways that logging goes wrong. Later chapters cover the fixes in detail.
Why you log LLM calls at all
An LLM call is slow, costs money, and gives different answers to the same input. Ordinary web requests are cheap and repeatable, so you can often debug them by re-running them. LLM calls are neither, so the log is often the only record of what happened. Teams log them for five main reasons.
- Debugging. When a user reports a bad answer, you need to know which model handled the request, which settings it used, and whether the call failed or just returned something poor.
- Cost tracking. Providers bill by tokens. Without per-call token counts, you can't tell which feature or customer drives your spend.
- Latency and reliability. Logged latency and status codes show slow calls, timeouts, rate limits, and retries.
- Quality evaluation. To improve prompts, you compare outputs across prompt versions. That needs a record of what was sent and returned.
- Audit and compliance. Some organizations must show what an automated system did and when.
Notice that only the last two reasons depend on the actual text of prompts and responses. Debugging, cost, and latency can all be served by metadata: the model name, token counts, durations, and status. That difference is the basis for the policy in a later chapter.
What a naive approach looks like
The easiest way to log an LLM call is to write down everything. This code does exactly that.
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("llm")
def fake_llm(prompt: str) -> str:
# Stand-in for a real API call.
return "Thanks. I will email your invoice to the address on file."
def naive_call(prompt: str) -> str:
logger.info("prompt=%s", prompt)
response = fake_llm(prompt)
logger.info("response=%s", response)
return response
naive_call("My name is Ana Ruiz, my email is [email protected]. Where is my invoice?")Running it prints the user's name and email address into the log. Each line looks harmless, and it is useful the day you write it. The problem is what the log becomes once the application runs in production. It collects every prompt from every user.
What can go wrong
Logs differ from the database that holds your application data. They are written by many code paths and copied to many places. Far more people can read them, and they rarely have the same access controls or deletion rules. Putting prompt text into logs moves sensitive data into the least protected part of your system.
Personal data ends up in logs
Users type freely into LLM features. They paste emails, phone numbers, addresses, medical details, and account numbers. You may not have designed the feature to collect any of that, but the prompt box accepts it. In many jurisdictions, personal data in logs falls under the same privacy rules as personal data in your main database. That can include rights to access and delete it.
Secrets get copied into prompts and logs
Developers paste code, configuration files, and error output into prompts. These often contain API keys, database passwords, and tokens. Applications also build prompts from internal documents and tool output, which can carry secrets nobody noticed. Separately, request headers contain your own credentials, for example an Authorization: Bearer ... header. If you log the full request object from an HTTP client or SDK, you log your own API key.
Proprietary text leaks
Prompts often include internal documents, source code, contracts, or unreleased plans. The log pipeline may send that text to a third-party service for storage or search. Your LLM provider and your logging vendor then both hold the data, under different terms.
Responses contain sensitive data too
Responses are not safer than prompts. A model may repeat personal data from the prompt, from retrieved documents, or from earlier conversation turns. In a retrieval-augmented system, the response can quote text the current user was never meant to see. Logging the response copies that text into a second place.
Logs live longer than anyone expects
Application logs are often kept for months, shipped to a central system, and copied into backups. A prompt you thought of as temporary can outlive the user's account. Deleting a user's data from the database does not remove it from log archives.
Model output can attack the log
Model output is text produced from untrusted input. A user, or a document the model read, can steer the model into emitting a newline followed by a fake log entry such as INFO payment approved. If your log format is plain text, that fake line looks real. Later chapters cover this log injection problem. For now, remember that prompt and response text are untrusted data and must never be written to a log without treatment.
Logs are an attractive target
An attacker who cannot reach your database may still reach your logging system. Logs often hold unusually rich data and are guarded less carefully. A debug log containing prompts and keys can be the easiest thing to steal.
How the pieces connect
The following diagram shows how one logging call can spread sensitive data to several places.
One log line becomes at least six copies, each with its own access rules. Fixing a leak after the fact means finding and cleaning every one of them. Preventing the leak at the point of writing is much cheaper.
Logging versus not logging
The risk does not mean you should log nothing. Without logs, you can't debug failures, explain a bill, or investigate an incident. The aim is to log enough to run the system, and no more sensitive text than that requires. The table compares the common choices.
| Approach | Debugging value | Privacy risk | Typical use |
|---|---|---|---|
| Log nothing | Very low | Lowest | Rarely acceptable |
| Metadata only | Medium to high | Low | Default for production |
| Metadata plus redacted, truncated content | High | Medium | Short, approved debugging windows |
| Full prompts and responses | Highest | Highest | Local development with fake data |
Most production systems belong in the second row, and move to the third only for a stated reason and a limited time. The next chapters build toward that arrangement.
Common mistakes to watch for
These mistakes appear again and again in real projects. Check your own code for each one.
- Logging the full request or response object from an SDK, which can include headers and keys.
- Leaving a debug-level prompt log switched on in production because it was useful during development.
- Logging exception messages that embed the prompt text.
- Sending logs to a vendor before checking what the vendor stores and for how long.
- Assuming a user's prompt contains no personal data because the feature was "only for summarizing documents".
- Treating model output as trusted because the model is your own.
What the rest of the tutorial builds
You will build a small wrapper around an LLM call that logs structured metadata by default. It records the model, token counts, latency, status, and a request ID, plus a hash of the prompt so you can compare repeated requests without storing the text. When content is needed, the wrapper redacts personal data and secrets, truncates the text, and logs it only when someone has explicitly switched that on. It also handles streamed responses, sets retention and access rules for the stored logs, and includes tests that fail if redaction breaks.
Exercises
Exercise
A teammate says, "We only log prompts at INFO level, and our users are all employees, so there's no privacy problem." Give two reasons this reasoning is incomplete.
Show answer
First, log level only controls which lines are written, and INFO is usually enabled in production, so prompts are still stored and shipped to every system that receives the logs. Second, employees are still people with personal data, and their prompts may also contain customer data, secrets, or confidential company text. The log also has a wider audience, longer retention, and weaker access control than the application database, so the data is exposed to more people for longer.
Exercise
Name three reasons for logging LLM calls that can be served with metadata alone, without storing any prompt or response text.
Show answer
Cost tracking (token counts per call), latency and reliability monitoring (duration, status, retries), and basic debugging of failures (model name, error type, request ID). Quality evaluation and some audit needs are the reasons that more likely require content.