Skip to content

Module 07 · Lesson 7.3

Data Privacy, Sensitive Information and Secure Logging

40 minUpdated 18 Nov 2026Part of Safety, Security and Reliability · AI Agent Development
On this page
  1. What you will learn
  2. Why privacy matters for AI agents
  3. What must never go into prompts or logs
  4. What to log: who, what, when and outcome
  5. Redact emails and card numbers with Python
  6. Log retention and who may read the logs
  7. Conclusion and your next step
  8. Common errors and fixes
  9. Validation checklist
  10. Hands-on exercise
  11. Knowledge check
  12. Frequently asked questions
  13. References

Think of a shop's CCTV room. The recordings help when something goes wrong. But if they were left in an unlocked room and kept for ten years, they would become a danger of their own. A log file is like that recording. Useful, and risky if you keep too much for too long.

AI agents make this problem bigger, because customers type whatever they like into the chat: emails, phone numbers, even card numbers. This lesson shows what should never go into a prompt or a log, what to record instead, how to redact (blank out) sensitive text, and how long to keep logs. Most of it needs no coding. One short Python example redacts emails and card numbers.

What you will learn

  • List what must never go into prompts, logs and traces.
  • Log who, what, when and outcome without storing personal data.
  • Run a Python function that redacts emails and card-like numbers.
  • Set simple rules for log retention and access.

Before you start

Why privacy matters for AI agents

Personal data is any information that can point to a real person: a name, an email address, a phone number, a home address, an order history. Sensitive data is the riskier kind, such as card numbers, passwords, health details and secret keys. If it leaks, people can be harmed.

Data can leak in three places in an agent: the prompt that goes to the model provider, the reply that goes to the customer, and the logs that stay on your servers. This lesson focuses on prompts and logs. OWASP lists this problem as LLM02: Sensitive Information Disclosure (opens in a new tab).

Redaction
Replacing sensitive text with a harmless label before it is saved or shown. Example: sam@example.com becomes [email].
Log
A written record of what a program did, kept so people can investigate problems later.
Data minimisation
Collecting and keeping only the data you need for the job. If you do not store it, it cannot leak.
Retention
How long data is kept before it is deleted.

What must never go into prompts or logs

Start with a short "never" list and make it part of your code review. Anything on the list is stripped before it reaches the model or the log.

Never put in prompts or logsWhyDo this instead
API keys, passwords, tokensAnyone who reads the log can use themKeep them in the environment; never print them
Full card numbersDirect financial riskNever ask for them; redact to [card] if typed
Email addresses, phone numbers, home addressesThey identify a personRedact, or log an internal id instead
Full customer messagesThey may contain anythingLog a short redacted summary or a length
Other customers' order detailsWrong person could see themLook up only the asker's order
The full system prompt in every log lineBloats logs, may leak rulesLog a version label such as v2
The agent only needs an order id and a status to do its job. It does not need an email or a card.

Share the minimum with the model

In Context Design: What the Agent Needs at Each Step you learned to give the model only what each step needs. Privacy is the same rule. If the order status can be found without the customer's address, do not put the address in the prompt.

What to log: who, what, when and outcome

A good log answers four questions about each event, without needing personal data. When a customer complains, you should be able to see what happened from the log alone.

QuestionLog thisNot this
Who?A run id, an internal user idName, email
What?Step number, tool name, a short noteFull message text
When?A time stamp in a fixed formatNothing sensitive here
Outcome?ok true or false, status, error codeThe whole reply, if it holds personal data
Ids and outcomes are enough to find and fix most problems.

This matches the trace event you will meet in Module 9: a run id, a step, a kind, a name, a time and a yes-or-no result. Notice that no personal data is needed to fill those fields.

Redact emails and card numbers with Python

Redaction is your safety net. You try not to collect sensitive text, but customers will still type it. The rule for Quillfeather is simple: replace email addresses with [email] and 16-digit card-like numbers with [card] before anything is logged.

Pythonredact.py
import json
import re

EMAIL = re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+")
CARD = re.compile(r"\b\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}\b")


def redact(text):
    text = EMAIL.sub("[email]", text)
    return CARD.sub("[card]", text)


def log_line(run_id, step, tool, ok, message):
    entry = {
        "time": "2026-11-18T10:00:00Z",
        "run_id": run_id,
        "step": step,
        "tool": tool,
        "ok": ok,
        "note": redact(message)[:80],
    }
    return json.dumps(entry)


raw = "Hi, I am sam.lee@example.com. My card 4111 1111 1111 1111 was charged twice for QF-1042."
print("before:", raw)
print("after: ", redact(raw))
print(log_line("R-0001", 2, "lookup_order", True, raw))

Runs offline with Python 3.10 or later. The email and card number are made up.

What each part does

  • EMAIL is a regular expression, a small text pattern. It matches letters, dots and similar characters, then an @ sign, then a domain such as example.com.
  • CARD matches four groups of four digits, with an optional space or dash between them, so "4111 1111 1111 1111" and "4111-1111-1111-1111" are both caught.
  • redact replaces every email with [email] and every card-like number with [card], and returns the clean text.
  • log_line builds one log entry as a dictionary: a fixed time (fixed here so the output never changes), the run id, step, tool name and result.
  • redact(message)[:80] cleans the note first and then keeps only the first 80 characters, so a long message cannot flood the log.
  • json.dumps turns the entry into one line of text, ready to append to a log file.
OutputCaptured from a real run
before: Hi, I am sam.lee@example.com. My card 4111 1111 1111 1111 was charged twice for QF-1042.
after:  Hi, I am [email]. My card [card] was charged twice for QF-1042.
{"time": "2026-11-18T10:00:00Z", "run_id": "R-0001", "step": 2, "tool": "lookup_order", "ok": true, "note": "Hi, I am [email]. My card [card] was charged twice for QF-1042."}

The order number stayed, because it is useful and is not on the never list. The email and card number are gone.

Log retention and who may read the logs

Logs are a store of data, so they need the same care as a database. Two decisions matter most: how long you keep them and who can open them.

  • Keep logs only as long as you need them. Pick a number of days that fits your investigation needs and your organisation's policy, then delete older logs automatically.
  • Limit who can read them. Not every developer needs access to production logs. Give access to the few people who investigate incidents.
  • Store logs safely. Use protected storage, not a shared folder or a chat message.
  • Keep secrets out entirely. If an API key lands in a log by mistake, treat the key as leaked and replace it.
  • Record access. Know who looked at the logs and when.

These habits agree with OWASP's Logging Cheat Sheet (opens in a new tab), which also lists data that should be removed or masked before logging. Memory and stored conversations follow the same thinking, as shown in Memory Retention, Privacy and Data Lifecycle.

Conclusion and your next step

Collect little, send little, log little. Write a never list, log who, what, when and outcome, and redact what slips through. Keep logs for a limited time and let only a few people read them.

Your next step: open a log or trace from one of your labs and mark every piece of personal data in it. Then continue to Output Validation and Policy Enforcement, where code checks the agent's replies before they leave.

Want more? Read Authentication, Secrets and Least-Privilege Access for handling keys, and the Agent Launch Safety Checklist.

Common errors and how to fix them

Full customer messages appear in the logs.

Why it happens: The whole prompt or reply was logged for convenience while debugging.

Fix: Log ids, step names and outcomes. If you need text, redact it and cut it short.

An API key shows up in a log line.

Why it happens: A request or error was printed with its headers.

Fix: Never print headers or environment values. Replace the leaked key and add a check to your code review.

Redaction misses some card numbers.

Why it happens: The pattern expects one layout, but customers write digits in many ways.

Fix: Add test cases for each layout, and also stop collecting card numbers: the agent should say it never needs them.

Old logs pile up forever.

Why it happens: Nobody set a retention period or a deletion job.

Fix: Choose a retention period with your organisation's policy and delete older logs automatically.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Add phone numbers to the redactor

Extend redact.py so that UK-style phone numbers such as 07700 900123 become [phone]. Then write a log line for a failed return request that contains no personal data.

You will need

  • Test message: "Call me on 07700 900123 or email sam.lee@example.com about QF-1044."
  • A phone number here is 11 digits starting with 07, with an optional space after the fifth digit.
  • The failed request is for QF-1044 with reason changed_mind; the tool returned an error.
  • Use the log_line function from the lesson.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Add a PHONE pattern such as r"\b07\d{3} ?\d{6}\b" and one more replace call.
  • Run the function on the test message and read the result carefully.
  • Use a short note such as "return refused: outside 30 days" instead of the customer's text.
Show a model answer

Add PHONE = re.compile(r"\b07\d{3} ?\d{6}\b") and a third replacement with "[phone]" inside redact. The test message becomes "Call me on [phone] or email [email] about QF-1044." The order id stays, which keeps the log useful. For the log line, call log_line("R-0002", 3, "request_return", False, "return refused: outside 30 days"). The note comes from your own code, so it holds no personal data, and the redaction inside log_line is a second safety net. Remember that patterns miss formats you did not test, so keep the never list as the first defence.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Which log entry is the best practice?
    Show the answer and explanation

    Answer: B. The second option gives you enough to investigate and holds no personal data. No logging is tempting for safety, but then you cannot find out what went wrong.

  2. 2.Why is redaction described as the last layer, not the first?
    Show the answer and explanation

    Answer: A. Pattern matching only catches the layouts you tested. The stronger layers are not collecting the data, not sending it to the model and not logging full messages.

  3. 3.What should you do if an API key is written into a log by mistake?
    Show the answer and explanation

    Answer: B. Anyone who could read the log may have seen the key. Deleting the line is tempting, but copies and backups may exist, so the key must be replaced.

Frequently asked questions

Can I send customer data to an AI model?

It depends on your organisation's policy, the provider's terms and the laws where you work. As a habit, send the minimum the step needs and leave out what the task does not require. Ask your privacy or legal team when unsure.

What should an AI agent log?

Enough to investigate: a run id, the step, the tool name, the time and whether it worked. Add a short redacted note if it helps. Leave out full messages, secrets and personal data.

What does redact mean?

It means replacing sensitive text with a harmless label before saving or showing it. For example, an email address becomes [email]. The label shows something was there without revealing it.

How long should I keep logs?

Only as long as you need them for investigation and your policy allows. Choose a number of days with your team, then delete older logs automatically. Shorter is safer for privacy.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.