Sub topic 4
Structured logs as the foundation
This chapter assumes you can call an LLM API, know Python's logging module and log levels, and have met JSON before. Every later chapter adds fields to the log record. This one sets up the record itself.
Why plain text logs fall short
A typical text log line looks like this:
2026-11-28 06:57:54 INFO call to demo-model finished in 412 ms, status okA person can read it, but a program has to parse it with a regular expression. That parsing breaks as soon as someone rewords the message. Text lines also mix your words with data you don't control. If a prompt or model reply contains a newline, one call can produce several lines, and some of them may look like entries you never wrote.
A structured log writes each event as one machine-readable record, usually one JSON object per line. Each field has a name, so you can filter on status or latency_ms without parsing text.
What you gain
- Querying. Log tools can filter and aggregate by field, for example "all calls with
status = errorformodel = demo-model". - A fixed schema. The fields you allow are written in code. A reviewer can see at a glance whether anything sensitive can reach the log.
- Safe encoding.
json.dumpsescapes newlines and quotes inside values. Untrusted text stays inside its own field and cannot start a new log line. The log injection chapter covers this in more detail.
A minimal JSON formatter
Python's logging module lets you control the output format with a Formatter. This one turns each record into a single JSON line and reads extra fields from an extra={"fields": ...} argument.
import json
import logging
import sys
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
entry = dict(getattr(record, "fields", {}))
entry.update({
"ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%S"),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
})
return json.dumps(entry, default=str)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logger = logging.getLogger("llm")
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info("llm_call", extra={"fields": {"model": "demo-model", "status": "ok", "latency_ms": 412}})
logger.info("llm_call", extra={"fields": {"note": "line one\nFAKE line"}})Both calls print exactly one line each. In the second, the newline appears as \n inside the string, so the fake line never exists.
Common errors
- Using f-strings as the log message.
logger.info(f"prompt={prompt}")puts unvalidated text into the message. Keep the message a constant event name and put values in named fields. - Letting fields overwrite core keys. The formatter above applies
ts,level,logger, andmessagelast, so a field with one of those names can't replace them. - Dumping whole objects. Passing a full request or response object as a field can log headers and bodies you never meant to keep. Build the field dictionary yourself from an approved list.
- Forgetting
default=str. Without it, one value that isn't JSON-serializable, such as adatetime, raises an error inside your logging path. - Inconsistent names.
latency_msin one place anddurationin another makes queries harder. Pick names once and reuse them.
Exercise
A teammate logs logger.info(f"response: {reply}") and the model reply contains a newline followed by "ERROR payment failed". Why is this a problem, and how does a structured log avoid it?
Show answer
The newline splits the output into two lines, and the second looks like a real ERROR entry that someone could mistake for a genuine event. With a structured log, the reply goes into a named field, and json.dumps escapes the newline as \n. The whole record stays on one line, and the text is only ever the value of that field.