Sub topic 9
Treating prompts and model output as untrusted log input
This chapter assumes you can write basic Python, have called an LLM API, know application logging and log levels, and can read simple regular expressions. It builds on structured logging, which the previous chapters introduced.
Why model text is untrusted
A prompt often contains text a user typed or a document someone else wrote. A model response is generated from that prompt. Neither is under your control. If you paste either into a log line, whoever wrote that text can influence what your log file looks like.
This is called log injection. An attacker, or a model that was steered by one, includes a newline in the text. The newline ends your real log line. What follows looks like a new entry that your application never wrote.
What the attack looks like
Suppose you log with an f-string in a plain-text format:
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("llm")
response = "Here is your summary.\n2026-11-28 07:00:00,000 INFO admin login ok user=root"
logger.info(f"response={response}")The output has two lines. The second one looks like a genuine record of an admin login. Anyone reading the file, or a tool parsing it by line, cannot tell the difference.
The fix: encode, don't concatenate
Put untrusted text in a field of a structured record and let a serializer escape it. json.dumps turns a newline into the two characters \n, and it escapes quotes and control characters. The record stays on one line, and the text stays inside its field.
import json
import logging
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger("llm")
response = "Here is your summary.\n2026-11-28 07:00:00,000 INFO admin login ok user=root"
logger.info(json.dumps({"event": "llm_response", "response": response}))The output is a single line. The fake entry is now inert text inside the response value. This is why the wrapper from earlier in the tutorial builds a dictionary and calls json.dumps once, in the finally block, rather than formatting strings by hand.
Other places injection hides
- Field names. If you build keys from untrusted data, an attacker can add or overwrite fields. Use fixed key names and put untrusted text only in values.
- Log viewers. A dashboard may render values as HTML or follow links. Escape output in the viewer too. Escaping at write time does not protect a viewer that decodes it again.
- Downstream parsers. Tools that split on spaces or commas can be fooled by values that contain those characters. JSON lines avoid most of this.
- Terminal control codes. Escape sequences in text can change what a terminal shows when someone runs
caton the log.json.dumpsescapes control characters such as\x1b, so this is covered when you use it.
Also bound the size
A model can return very long text, and a user can send a very long prompt. Truncating logged content, as the wrapper does with [:2000], limits both storage cost and the room an attacker has to flood your logs. Truncate after redaction only if your patterns cannot be split by the cut. Otherwise a secret cut in half may escape its pattern.
Exercise
A teammate logs with logger.info("response=" + response) and says the model is trusted, so it is fine. Give two reasons this is still unsafe, and name the fix.
Show answer
First, the response is generated from prompts that may include attacker-controlled text, so the model can be steered into emitting newlines and fake log entries. Second, the model may reproduce text from a document or user message that contains such content. The fix is to build a dictionary with fixed keys, put the response in a value, and write it with json.dumps so newlines and control characters are escaped.