Sub topic 14
Logging and monitoring guardrail decisions
This chapter assumes you can write basic Python, call an LLM through an SDK, and read JSON. It also assumes you know the input and output checks from earlier chapters. Here you will record what each guardrail decided, so you can see how it behaves in production and catch problems early.
Why log guardrail decisions
A guardrail that blocks a request leaves no trace unless you log it. Without logs you cannot tell whether a rule fires too often, never fires, or breaks after a model update. The false positive and false negative rates from the evaluation chapter come from a test set. Logs show how the guardrail behaves on real traffic.
Each check should produce one structured record. Structured means one JSON object per event with fixed field names, so you can filter and count the records later.
What to record
| Field | Purpose |
|---|---|
| `request_id` | Links the input check, model call and output check |
| `stage` | `input` or `output` |
| `check` | Name of the rule or classifier |
| `action` | `allow`, `block`, `redact`, `retry` or `fallback` |
| `reason` | Short code, such as `too_long` |
| `latency_ms` | Time the check took |
| `timestamp` | When the check ran |
Write the records
The sketch below wraps a check and logs its outcome. It reuses the GuardResult idea from earlier.
import json
import logging
import time
import uuid
from dataclasses import dataclass
logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger("guardrails")
@dataclass
class GuardResult:
allowed: bool
reason: str = ""
def check_input(text: str) -> GuardResult:
if len(text) > 4000:
return GuardResult(False, "too_long")
return GuardResult(True)
def logged_check(request_id: str, stage: str, name: str, check, text: str) -> GuardResult:
start = time.perf_counter()
result = check(text)
record = {
"request_id": request_id,
"stage": stage,
"check": name,
"action": "allow" if result.allowed else "block",
"reason": result.reason,
"latency_ms": round((time.perf_counter() - start) * 1000, 2),
"timestamp": time.time(),
}
log.info(json.dumps(record))
return result
request_id = str(uuid.uuid4())
logged_check(request_id, "input", "length", check_input, "x" * 5000)Running this prints one JSON line with "action": "block" and "reason": "too_long".
Protect user data in logs
Do not log the raw prompt by default. It may contain the personal data you just redacted. Log the redacted text, a hash, or only the metadata above. If you keep samples for review, store them with restricted access and a short retention period.
What to monitor
Turn the logs into a few numbers and watch them over time:
- Block rate per check. A sudden rise can mean an attack, a new kind of user, or a rule broken by a code change. A drop to zero can mean the check no longer runs.
- Retry rate. A high rate for structured output validation suggests the prompt or model changed.
- Fallback rate. This shows how often users get a degraded answer.
- Check latency. Track the 95th percentile, not only the average, because slow outliers are what users notice.
Set alerts on large changes from a baseline, not on fixed numbers you guessed in advance.
Close the loop
Sample some blocked requests and some allowed ones for human review. Blocked samples reveal false positives. Allowed samples reveal false negatives that the guardrail missed. Add confirmed mistakes to your evaluation set so the next change to a rule is tested against them.
Exercise
Your block rate for the prompt-injection check drops from 2% to 0% overnight, and no alert fires. Name two possible causes and one log field or metric that helps you tell them apart.
Show answer
One cause is that attacks stopped, which is unlikely to be exact zero. Another is that the check no longer runs, for example after a deploy that removed it or an exception that skips it. Compare the count of records for that check name with total requests. If the check has no records at all, it is not running. If it has records with only allow, it runs but never matches. Also add an alert for a check that stops producing records.