Sub topic 19
Logging, monitoring and incident response
This chapter assumes you have read the earlier chapters on trust boundaries, tools and agents, and defense in depth. You should be comfortable reading Python and know what a structured log line is.
The earlier defenses reduce the chance and the impact of an injection. None of them reduces either to zero. Logging and monitoring answer the next question: how do you find out that an injection succeeded, and what do you do then?
Why detection matters here
A prompt injection rarely produces an error. The model returns fluent text, a tool call succeeds, and every HTTP status is 200. Without records of what the model saw and did, you cannot tell a normal session from a compromised one.
Logs also support the other defenses:
- Red-team findings become regression tests only if you can reproduce the failing input.
- Approval prompts are only meaningful if you can review what was approved.
- Incident response depends on knowing which data and tools a session touched.
What to log
Log at each trust boundary, not only at the model call. A useful record links all of the following with one request ID:
| Event | Fields worth keeping | Why |
|---|---|---|
| Input received | user ID, source type (user, web, email, retrieval), content hash | Shows where untrusted text entered |
| Retrieval | document IDs, source URLs, scores | Traces a poisoned document |
| Model call | model name, prompt version, token counts | Reproduces behavior after a prompt change |
| Tool call | tool name, arguments, allow or deny decision, approver | Shows what the model tried and what policy did |
| Output delivered | sanitizer actions, removed URLs or images | Shows blocked exfiltration attempts |
Prefer hashes and document IDs over raw content when the content is sensitive. Keep a way to retrieve the full text for a limited time under access control, because responders will need it.
A minimal audit layer
The following code records tool decisions and output checks as JSON lines. It flags replies that contain links to hosts outside an allowlist, which is the pattern the exfiltration chapter described.
import json
import logging
import re
import time
import uuid
from urllib.parse import urlparse
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger("llm_audit")
ALLOWED_HOSTS = {"images.example.com", "docs.example.com"}
URL_RE = re.compile(r"https?://[^\s)\"'>]+")
SECRET_RE = re.compile(r"(sk-[A-Za-z0-9]{8,}|AKIA[0-9A-Z]{16})")
def redact(text: str) -> str:
return SECRET_RE.sub("[REDACTED]", text)
def audit(event: str, request_id: str, **fields) -> None:
record = {"ts": round(time.time(), 3), "event": event, "request_id": request_id}
record.update(fields)
logger.info(json.dumps(record))
def check_reply(request_id: str, reply: str) -> list[str]:
"""Log and return URLs in the reply that point outside the allowlist."""
suspicious = []
for url in URL_RE.findall(reply):
if urlparse(url).hostname not in ALLOWED_HOSTS:
suspicious.append(url)
if suspicious:
audit("suspicious_output", request_id, urls=[redact(u) for u in suspicious])
return suspicious
request_id = str(uuid.uuid4())
audit("tool_call", request_id, tool="send_email", decision="denied")
check_reply(request_id, "See ")Every line shares the request_id, so a responder can pull the whole chain with a single search.
What to monitor
Monitoring turns logs into signals. Choose signals that reflect the attack paths from earlier chapters:
- Denied tool calls. A spike in policy denials suggests the model is being steered toward actions you do not allow.
- Output to unknown hosts. Links or images pointing outside the allowlist are a strong exfiltration indicator.
- Canary hits. Plant a unique string in the system prompt or in a sensitive document. If it appears in an output or an outbound request, something leaked.
- Unusual tool volume. One session that calls a search or email tool dozens of times differs from the baseline.
- Repeated refusals or odd phrases. Text like "ignore previous instructions" in retrieved documents is worth flagging, even though attackers can rephrase it.
Keyword matching on inputs is a weak signal alone, for the same reasons given in the filtering chapter. Treat it as one input to an alert, and weight behavioral signals (denied actions, unexpected egress) higher.
Responding to an incident
Decide the steps before you need them. A workable sequence has five stages.
- Detect. An alert fires or a user reports odd behavior. Record the request ID.
- Contain. Disable the affected tool, revoke the scoped credential the session used, or remove the poisoned document from the index. Containment should be a switch you can flip without a deploy.
- Investigate. Reconstruct the chain: which untrusted source entered, which tools ran, what data left. Determine whether other sessions retrieved the same document.
- Remediate. Rotate exposed credentials, notify affected users as your obligations require, and fix the gap, such as a missing allowlist entry or a tool that needed approval.
- Add a regression test. Turn the payload into an entry in your injection test suite so the failure cannot return unnoticed.
Common mistakes
- Logging only the final answer, so the retrieved documents and tool arguments are lost.
- Storing raw prompts forever in a widely readable bucket.
- Alerting on every suspicious phrase, which trains the team to ignore alerts.
- Having no way to disable one tool without redeploying the whole application.
- Treating a quiet dashboard as proof of safety. Monitoring finds what you thought to look for.
Exercise
An email-summarizing assistant has a sendemail tool that requires human approval. Last night the logs show three denied sendemail calls to an unfamiliar address, all in sessions that summarized messages from one external sender. Name two things you do during containment and one thing you add afterward.
Show answer
Containment: quarantine or block messages from that sender (and remove any already indexed), and disable or tighten the sendemail tool, or revoke the credentials those sessions used, until you understand the scope. Afterward: add the observed payload to the injection regression test suite, and also add an alert for repeated denied tool calls so the next attempt is noticed sooner. Investigating whether any approved sendemail calls went to the same address is also a sound step.