Sub topic 4
Structured logs as the foundation
Every later chapter in this tutorial adds a safeguard to your logs: redaction, truncation, hashing, retention. Those safeguards work only if your log records have a predictable shape. This chapter builds that shape.
This chapter assumes you can write basic Python, know the standard logging module and its levels, and have called an LLM API. It does not assume you have used a log aggregation tool.
Plain-text logs versus structured logs
A plain-text log line is a sentence with values pasted into it:
INFO LLM call to gpt-x took 850 ms for user [email protected], prompt: Summarize my contract...A person can read this. A program has to guess where each value starts and ends. Worse, the user's email and prompt are fused into the message, so you cannot treat them differently from the harmless values.
A structured log writes each event as a record with named fields. The most common format is JSON Lines, where each line is one complete JSON object:
{"ts": "2026-11-28T06:48:47+00:00", "level": "INFO", "event": "llm_call", "model": "gpt-x", "latency_ms": 850, "prompt_chars": 412}| Property | Plain text | Structured (JSON Lines) |
|---|---|---|
| Finding slow calls | Regular expression over prose | Filter `latency_ms > 2000` |
| Handling sensitive values | Mixed into the sentence | Each field can be allowed, redacted, or dropped by name |
| Format drift | Any code change can break parsers | A schema you can test |
| Multi-line input | Breaks one event into many lines | JSON escapes newlines, so one event stays on one line |
The third row matters for safety. If a field named prompt exists, you can write a rule such as "never emit prompt unless content logging is on." You cannot write that rule for text buried in a sentence.
One event, one line, one schema
Three conventions keep structured logs useful.
- One event per line. Each line is a complete JSON object. Collectors split on newlines, so a record spread across lines gets corrupted.
- A constant event name. Use a short fixed string such as
llm_callas the message. Do not build the message with an f-string that contains values. The values go in fields. A constant name lets you count and alert on events, and it keeps content out of the free-text part of the record. - Stable field names and types.
latency_msis always an integer in milliseconds. It is never"850ms"in one place and0.85in another. Aggregators often index a field by the type of the first value they see, and a later mismatch can cause records to be dropped or misparsed.
A small set of fields appears on every record:
ts: a UTC timestamp in ISO 8601 format.level: the log level.logger: which component wrote it.event: the constant event name.
Event-specific fields, such as model or status, are added on top. The next chapters define which of those fields to include.
Building a JSON formatter with the standard library
You do not need a third-party package. Python's logging module lets you control output through a Formatter. The formatter below turns any record into one JSON line and includes the fields passed through extra=.
import json
import logging
import sys
from datetime import datetime, timezone
# Attribute names that every LogRecord already has. Anything else
# on the record came from the caller's extra= argument.
_STANDARD_ATTRS = set(
logging.LogRecord("", 0, "", 0, "", (), None).__dict__
) | {"message", "asctime", "taskName"}
def _safe_default(obj):
# Never fall back to str(obj): that could dump an object's contents.
return f"<{type(obj).__name__}>"
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
entry = {
"ts": datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
"level": record.levelname,
"logger": record.name,
"event": record.getMessage(),
}
for key, value in record.__dict__.items():
if key not in _STANDARD_ATTRS:
entry[key] = value
if record.exc_info and record.exc_info[0] is not None:
# Log the exception type only. Exception messages and
# tracebacks can contain prompt text.
entry["error_type"] = record.exc_info[0].__name__
return json.dumps(entry, default=_safe_default)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logger = logging.getLogger("llm")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.propagate = False
logger.info(
"llm_call",
extra={"model": "gpt-x", "latency_ms": 850, "prompt_chars": 412, "status": "ok"},
)Running it prints one line similar to this (the timestamp will differ):
{"ts": "2026-11-28T06:48:47.113000+00:00", "level": "INFO", "logger": "llm", "event": "llm_call", "model": "gpt-x", "latency_ms": 850, "prompt_chars": 412, "status": "ok"}Four choices in this formatter are deliberate.
- The event name is the message. The call passes the constant
"llm_call". Nothing is interpolated into it. default=_safe_default.json.dumpsraises an error on types it cannot serialize, such as a response object from an SDK. The common fix isdefault=str, butstr()on an SDK object often prints its full contents, including the response text. Printing only the type name is safer and still tells you what went wrong.- Only the exception type is logged. Library exceptions sometimes embed the request body in their message. The type name gives you a field to count without carrying that text.
propagate = False. Without it, the record would also reach the root logger's handler and be printed a second time in a different format, possibly bypassing your safeguards.
The formatter also sets up the later chapters. Redaction and truncation can be added in one place, between "gather fields" and json.dumps, so every record passes through them.
Gotchas with `extra=`
The extra argument has three behaviors that surprise people.
Reserved names raise an error. Passing extra={"name": "x"} or extra={"message": "x"} raises KeyError: "Attempt to overwrite 'name' in LogRecord". Pick field names that avoid the standard attributes. Names like model_name or msg_chars are safe, and msg is not.
Fields are not filtered. The formatter above prints every extra field. If a developer writes extra={"prompt": prompt}, the full prompt is logged. A formatter alone does not enforce your policy. Later chapters add a gate that only passes approved fields. For now, review every extra= call as you would review a database query.
Nested values are risky. It is tempting to log extra={"request": request_dict} because it is easy. That dumps headers, which can include the Authorization header with your API key. Prefer flat fields you chose by name.
Types and schema discipline
JSON has few types: strings, numbers, booleans, null, arrays, and objects. Keep to these rules:
- Store durations as integers with the unit in the name:
latency_ms, notlatency. - Store counts as integers:
prompt_chars,response_chars. - Store status as a short string from a fixed set, such as
okorerror. Do not store free-form error text, which can carry user content. - Use
nullor omit the field when a value is unknown. Do not use-1or"n/a". - Use lowercase snake_case for all field names so queries stay predictable.
Adding a new field is usually safe. Renaming or retyping one breaks dashboards and alerts. If you must change meaning, add a new field name and retire the old one later.
Encoding and one-line guarantees
JSON escaping also helps with a safety problem. A model response may contain newline characters. In a plain-text log, a response like "ok\nINFO user=admin logged in" creates a second line that looks like a genuine event. With json.dumps, the newline becomes the two characters \n inside a string, and the record stays one line.
import json
response = "ok\nINFO {\"event\": \"admin_login\"}"
print(json.dumps({"event": "llm_call", "response": response}))
# {"event": "llm_call", "response": "ok\nINFO {\"event\": \"admin_login\"}"}This guarantee holds only if every record goes through the JSON encoder. A stray print() or an f-string log call with model output bypasses it. The chapter on log injection covers this in detail. For now, make it a rule that all application logging uses the structured logger.
Output destination
Write logs to standard output and let the platform collect them. This is the usual practice for containers and managed services. It keeps log rotation, shipping, and retention outside your application code, which is where the access and retention controls in a later chapter will be applied. If you write files yourself, set restrictive file permissions from the start.
Checklist for this chapter
- Each event is one JSON object on one line.
- The
eventvalue is a constant string. - Field names are stable snake_case, with units in the name.
- Reserved
LogRecordnames are avoided inextra=. - Serialization falls back to a type name and never to
str(obj). - Only exception types are logged, never messages or tracebacks.
- Nothing in the code path logs by
print()or by string interpolation of content.
Exercise
A teammate writes logger.info(f"llm_call model={model} reply={reply}") and says the log is "structured enough" because the formatter outputs JSON. Give two problems with this line and show a corrected call that logs the model, the reply length, and a status.
Show answer
First, the reply text is interpolated into the message, so the full response is logged and no field-level rule can exclude it. Second, the values are inside a sentence, so the model and length cannot be queried as fields, and a newline in the reply would be placed inside the event name. Corrected call: logger.info("llm_call", extra={"model": model, "response_chars": len(reply), "status": "ok"}). The event name is constant, the values are named fields, and the reply text is never logged.
Exercise
You call logger.info("llm_call", extra={"name": "gpt-x"}) and get a KeyError. Why does it happen, and what should you change?
Show answer
name is already an attribute of every LogRecord (it holds the logger's name), and logging refuses to overwrite standard attributes through extra. Rename the field to something that does not clash, such as model, and call logger.info("llm_call", extra={"model": "gpt-x"}).