Sub topic 14
Logging and Monitoring Guardrail Decisions
This chapter assumes you can write basic Python, use the standard logging and json modules, and have read the earlier chapters on rule-based checks, failure handling, and evaluation. Evaluation tells you how well a guardrail performed on a test set. Monitoring tells you how it behaves on live traffic after release.
Why guardrail decisions need their own records
A guardrail that blocks a request leaves the user with an error message and leaves you with nothing, unless you log the decision. Without records you cannot answer basic questions:
- Which check blocked this request?
- Did the block rate jump after yesterday's deploy?
- Is a new attack pattern getting through?
- Is a regex rejecting valid customers?
Live traffic also differs from your test set. Users write in new languages, paste long documents, and find phrasings your rules never saw. Monitoring is how you notice that drift. The false positive and false negative rates from the evaluation chapter go stale unless you keep measuring.
What to record for each decision
Log one record per check, not one per request. A single request may pass the length check, get redacted by the PII check, and fail the JSON validator. Those are three events, and you want all of them.
| Field | Example | Purpose |
|---|---|---|
| `request_id` | `9f1c...` | Joins all events from one request |
| `stage` | `input` or `output` | Shows which checkpoint fired |
| `check` | `pii_redaction` | Names the specific guardrail |
| `action` | `allow`, `block`, `redact`, `retry`, `fallback` | The decision taken |
| `reason` | `possible prompt injection` | Human-readable cause |
| `latency_ms` | `3.2` | Feeds the cost and latency review |
| `check_version` | `pii-v4` | Ties behavior changes to rule changes |
| `text_hash` | `a3f9...` | Lets you find repeats without storing content |
The action field should use the same vocabulary as your failure-handling policy. If the code can block, redact, retry, or fall back, the log should say which one happened.
Logging without creating a new leak
Guardrails often exist because the text contains sensitive data. Writing that raw text to a log file moves the problem somewhere with weaker access controls. Consider these options:
- Log a hash or short fingerprint instead of the text. You can still count repeats and match records to a reported incident.
- Log the redacted text, never the original.
- Sample full text for review into a separate store with strict access and a short retention period.
- Log which pattern matched and how many times, not the matched value.
A structured decision logger
JSON lines are easy to ship to any log platform and to query later. The sketch below logs each check as one JSON object and keeps raw text out of it.
import hashlib
import json
import logging
import time
import uuid
logger = logging.getLogger("guardrails")
logging.basicConfig(level=logging.INFO, format="%(message)s")
def fingerprint(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
def log_decision(request_id, stage, check, action, text, reason="", started=None):
latency_ms = round((time.perf_counter() - started) * 1000, 2) if started else 0.0
logger.info(json.dumps({
"ts": time.time(),
"request_id": request_id,
"stage": stage,
"check": check,
"action": action,
"reason": reason,
"latency_ms": latency_ms,
"text_hash": fingerprint(text),
}))
def length_check(text: str, request_id: str) -> bool:
started = time.perf_counter()
ok = len(text) <= 4000
log_decision(
request_id, "input", "length_limit",
"allow" if ok else "block", text,
reason="" if ok else "input too long", started=started,
)
return ok
rid = str(uuid.uuid4())
length_check("hello", rid)
length_check("x" * 5000, rid)Each call prints one JSON line. The second shows "action": "block" and "reason": "input too long". The same request_id ties the two lines together if you pass the same ID through a whole request.
Generate the request ID once at the entry point and pass it down. Creating a new ID inside each check makes events impossible to join.
Metrics worth tracking
Individual log lines help with debugging. Aggregated metrics help you spot trends. Compute these per check, over a time window:
| Metric | What a change can mean |
|---|---|
| Block rate | A spike may mean an attack or a broken rule. A drop may mean a check silently stopped running. |
| Redaction rate | More redactions suggest users are sending more personal data. |
| Retry rate (structured output) | A rise often follows a model or prompt change. |
| Fallback rate | Shows how often users get the degraded path. |
| p95 latency per check | Catches a classifier or judge call that has become slow. |
| Judge or classifier disagreement | Compares rule-based and model-based verdicts on the same input. |
Track the rate of each action as a share of requests that reached the check. Raw counts rise with traffic and tell you little on their own.
A block rate near zero is not good news by default. It may mean the check never runs, or that attackers found a bypass. Watch for both extremes.
Alerting on shifts
Alert on changes relative to a recent baseline, not just fixed numbers. The monitor below keeps a rolling window of recent outcomes and flags when the block rate exceeds a threshold. It waits for a minimum number of samples so a few early blocks do not trigger a false alarm.
from collections import deque
class BlockRateMonitor:
def __init__(self, window=100, threshold=0.2, min_samples=50):
self.events = deque(maxlen=window)
self.threshold = threshold
self.min_samples = min_samples
def record(self, blocked: bool) -> bool:
"""Record one outcome. Return True if the block rate is too high."""
self.events.append(blocked)
if len(self.events) < self.min_samples:
return False
rate = sum(self.events) / len(self.events)
return rate > self.threshold
monitor = BlockRateMonitor()
for _ in range(50):
monitor.record(False)
blocked_count = 0
while True:
blocked_count += 1
if monitor.record(True):
print(f"alert after {blocked_count} blocked requests")
break
# alert after 13 blocked requestsAfter 50 allowed requests, the alert fires on the 13th consecutive block, when the rate reaches 13 of 63, about 20.6%. In production you would send the alert to a pager or chat channel instead of printing it, and keep one monitor per check so you know where the shift occurred.
Turning records into improvements
Monitoring only pays off if it feeds back into the guardrails. The loop looks like this:
The review step matters most. Sample blocked requests and read them. If many look legitimate, you have false positives. Sample allowed requests that a later check or a user complaint flagged. If harmful content passed, you have false negatives. Add every confirmed case to your evaluation set, so the next rule change is tested against real failures.
Common errors
- Logging raw sensitive text. This is the most frequent mistake. Redact or hash before writing.
- Logging only blocks. You need allow events to compute rates. Without them you cannot tell a 5% block rate from a 50% one.
- No version field. When behavior changes, you cannot tell whether traffic changed or someone edited a rule.
- One log line per request. It hides which of several checks fired and makes per-check latency impossible to measure.
- Alerting on counts, not rates. A busy day looks like an attack.
- Never reading the logs. Dashboards that nobody reviews will not catch false positives, because blocked users rarely report them.
- Unbounded retention. Keep decision logs only as long as you need them, and keep sampled text for less time than metadata.
- Monitoring that can break the request. A failure in the logging code should never crash the model call. Wrap logging so errors are swallowed or reported separately.
Exercise
Your output validator for the JSON ticket format shows a retry rate that rises from 3% to 25% the day after a prompt change, while the block rate stays flat. Name two fields from the decision log that help you investigate, and say what you would do first.
Show answer
The check_version field (or deploy marker) and the reason field on the retry events help most. check_version confirms whether the validator itself changed or only the prompt did. reason shows which validation error repeats, for example "priority must be low, medium or high". First compare the retry reasons before and after the change, then sample the failing outputs, which the log lets you find through text_hash and a separate sampled store. Fix the prompt so the model produces the expected values, or loosen the validator if the new values are legitimate. Keep recording the retry rate to confirm it returns to the baseline.
Exercise
A teammate proposes logging the full user prompt for every blocked request so reviewers can see exactly what happened. What risk does this create, and what is a safer alternative?
Show answer
Blocked prompts often contain the sensitive data or hostile content the guardrail was built to catch, so storing them in ordinary logs spreads that data to anyone with log access. A safer approach logs the check name, reason, and a hash. It stores a redacted sample of the text in a restricted store with a short retention period for human review.