Without the right LLM logs a security team cannot tell whether a prompt injection succeeded, which tool an agent called with whose authority, or what data left in a response; with the wrong logs it builds a new store of personal data and secrets that is itself a breach waiting to happen. LLM traffic differs from ordinary application logging because the payload is free text written by users, retrieved from documents or produced by a model, and any of it can carry customer records, credentials or attacker instructions. This guide sets out a security logging record for LLM and agent calls, what to redact before storage, how to set retention and access against privacy law, how to protect logs from tampering, and the detection and investigation use cases that justify the collection. It is written for AI platform and security engineers. For tracing, cost and quality monitoring, see the LLM Observability Guide; this page covers the security and evidence side.
Key takeaways
- Log metadata always, content deliberately. Identity, model, tool calls, token counts and guardrail verdicts belong in every record; full prompt and response text should be captured only where a named use case needs it.
- Identity is the field most teams miss. Record the end user, the calling application or agent, and the credential used, or an investigation cannot say who caused a tool call.
- Redact before the first write. Secrets and personal data must be removed or tokenised in the pipeline, before logs reach any backend, because every downstream copy inherits whatever was stored.
- Retention is a privacy decision as well as a security one. Keep content short-lived and metadata longer, write the periods into a schedule, and check them against data protection law and any AI Act obligations that apply.
- Protect logs like evidence. Write-once storage, separate access for the people who read content, and monitoring of log access stop an insider or attacker from editing the record.
Why LLM logging is different
- The payload is untrusted and sensitive at once: a single request can hold a user's personal data, a retrieved contract and a hidden instruction from a web page. OWASP's LLM02:2025 Sensitive Information Disclosure and LLM07:2025 System Prompt Leakage apply to your own logs as much as to model output.
- Actions happen inside the call: agents call tools, query data stores and hand off to other agents. Under LLM06:2025 Excessive Agency, the tool call is the security event that matters, not the chat text.
- Logs are an injection target: attacker-supplied text flows straight into log lines. The OWASP Logging Cheat Sheet's advice on structured formats such as JSON and on sanitising CR, LF and delimiter characters applies directly.
- Standards are still moving: the OpenTelemetry GenAI semantic conventions are the closest common schema, but their status is Development and the attribute names may change. Pin the version you implement.
What to capture
The table lists a security logging record for each model call and each tool call. OpenTelemetry attribute names are given where one exists (from the GenAI semantic conventions repository, checked November 2026); use them so logs can be correlated across gateways, SDKs and SIEM.
| Field | OpenTelemetry attribute | Why security needs it | Default |
|---|---|---|---|
| Timestamp, trace and span ID | Standard span fields | Ordering events and joining model, tool and retrieval steps | Always |
| End user identity (pseudonymous ID) | None in GenAI set: use your own user or enduser attribute | Who initiated the request | Always |
| Calling application, agent and version | gen_ai.agent.id, gen_ai.agent.name, gen_ai.agent.version | Which workload acted, and whether it changed | Always |
| Credential used (key ID or service principal, never the secret) | None in GenAI set | Detecting stolen or misused API keys and tokens | Always |
| Provider, requested and actual model | gen_ai.provider.name, gen_ai.request.model, gen_ai.response.model | Unapproved model use, unexpected fallback | Always |
| Operation and conversation | gen_ai.operation.name, gen_ai.conversation.id | Rebuilding a multi-turn attack | Always |
| Token counts | gen_ai.usage.input_tokens, gen_ai.usage.output_tokens | Abuse, extraction and runaway cost (LLM10:2025 Unbounded Consumption) | Always |
| Finish reason and response status | gen_ai.response.finish_reasons | Content filter hits, truncation, refusals | Always |
| Guardrail and classifier verdicts | Custom attributes | Injection, jailbreak and data loss signals | Always |
| Tool name, type and call ID | gen_ai.tool.name, gen_ai.tool.type, gen_ai.tool.call.id | What the agent did | Always |
| Tool call arguments and result | gen_ai.tool.call.arguments, gen_ai.tool.call.result (Opt-In) | Which records, files or commands were touched | Arguments: redacted, usually yes. Results: by use case |
| Retrieval source IDs | gen_ai.data_source.id | Tracing indirect injection to the poisoned document | Always (IDs, not text) |
| System prompt version | gen_ai.prompt.name, gen_ai.prompt.version | Proving which instructions were live | Always (version, not text) |
| Input and output messages | gen_ai.input.messages, gen_ai.output.messages (Opt-In), or the _ref variants | Investigating what was asked and answered | By use case, redacted, short retention |
| System instructions and tool definitions | gen_ai.system_instructions, gen_ai.tool.definitions (Opt-In) | Detecting tampered prompts or tool lists | Store once per version, reference by hash |
The conventions mark message content, system instructions, tool definitions and tool call arguments and results as Opt-In. They also define _ref attributes holding a URI to content stored elsewhere. Use that pattern: keep a reference on the span and put the content in a separate store with stricter access and shorter retention.
Choosing a capture level: a small team running one internal assistant can usually log metadata plus redacted tool arguments and keep content off, switching it on per tenant during an investigation. A regulated organisation or one running agents with write access to business systems should capture redacted content for agent and tool steps, because reconstructing an incident without it is often impossible. Capturing at the AI Gateway gives one consistent record across applications; capturing in the agent framework adds tool and reasoning context the gateway cannot see. Most teams need both, joined by trace ID.
Redaction and sensitive data
The OWASP Logging Cheat Sheet says passwords, access tokens, encryption keys and connection strings should never be logged, and that sensitive personal data should be masked, hashed or encrypted, with pseudonymisation where the real identity is not needed. In LLM logs this has to happen automatically, because nobody can review free text by hand.
- Secrets first: run secret detection (provider key formats, JWTs, private key headers, connection strings, high-entropy strings) on prompts, responses and tool arguments, and replace matches with a type label such as [REDACTED:aws_access_key]. Alert on the match too: a secret in a prompt is an incident of its own. See the Secrets Management Guide.
- Personal data: detect names, email addresses, phone numbers, national identifiers, card numbers and health terms. Tokenise consistently (the same value maps to the same token) so investigators can still follow one customer through a session without seeing who they are.
- Fail closed on structure: where you can, keep an allow list of fields that may leave the application and drop anything else, rather than trying to block every bad pattern.
- Redact once, centrally: do it in the gateway or the telemetry collector, not in one SDK, so every exporter receives the same cleaned data.
- Keep a re-identification path under control: if investigators sometimes need the original, hold the token map or encrypted originals in a separate vault with dual approval and access logging.
- Test it: seed synthetic secrets and personal data into test prompts in every release and check none arrive in any log store.
The ICO reminds organisations that pseudonymised data is still personal data. Redaction lowers risk; it does not take the logs out of scope of data protection law.
Retention and access control
| Log tier | Contents | Example retention | Who can read |
|---|---|---|---|
| Security metadata | Identity, model, tokens, tool names, verdicts, source IDs | 12 months, or your security log standard | SOC, platform engineers |
| Redacted content | Prompts, responses, tool arguments after redaction | 30 days or less unless held for a case | Named investigators, on a ticket |
| Re-identification data | Token map or encrypted originals | Shortest period that supports investigations | Dual approval only |
| Legal hold | Records tied to an incident or dispute | Until the hold is released | Incident lead, legal |
These periods are examples, not legal advice. The legal drivers to check:
- Data protection law: under the UK GDPR and EU GDPR, data minimisation (Article 5(1)(c)) and storage limitation (Article 5(1)(e)) apply to prompt logs that hold personal data, and Article 32 requires appropriate security. The ICO's AI guidance says organisations "must not collect personal data on the off-chance that it might be useful in the future" and should set retention with a defined deletion point. The ICO notes that guidance is under review following the Data (Use and Access) Act. Logs are also in scope for access and erasure requests. See the AI and Privacy Guide.
- EU AI Act: Article 12 requires high-risk AI systems to "technically allow for the automatic recording of events (logs) over the lifetime of the system", Article 19 requires providers to keep those logs to the extent they control them, and Article 26(6) requires deployers to keep them for a period appropriate to the intended purpose "of at least six months". These apply to high-risk systems only, and their application dates have been subject to change; check the current position before relying on them.
- Sector rules: financial services and public sector record-keeping can require longer retention of decisions or customer communications. See the Log Retention Requirements Map.
Tamper protection
- Write once: ship logs off the application host quickly to object storage with object lock or another WORM control for the retention period, as the OWASP Logging Cheat Sheet advises (copy to read-only media as soon as practical).
- Integrity: hash-chain or sign log batches so gaps and edits are detectable; keep the signing key out of the application's reach.
- Separation: the AI platform team runs the pipeline but should not be able to delete or edit stored records. NIST SP 800-53 AU-9(4) limits management of audit information to a subset of privileged users.
- Monitor the monitors: log and alert on reads of the content tier, on retention or lock policy changes and on pipeline disablement.
Using logs for detection and investigation
| Use case | Signals in the log | Reference |
|---|---|---|
| Direct prompt injection and jailbreak attempts | Guardrail verdict spikes per user or key, repeated refusals followed by a success, unusual system prompt override phrasing | LLM01:2025, ATLAS AML.T0051, AML.T0054 |
| Indirect prompt injection | Tool calls or data access that follow retrieval of an external document in the same trace; new retrieval source IDs before a sensitive tool call | LLM01:2025, AML.T0051 |
| Excessive agency | Tool calls outside the agent's normal set, write or delete operations at unusual volume, calls on behalf of users who never asked | LLM06:2025 |
| Sensitive data exposure | Redaction counts on outputs, very long outputs to one caller, retrieval of restricted sources | LLM02:2025 |
| System prompt extraction | Outputs matching the stored system prompt hash or fragments | LLM07:2025 |
| Stolen keys and abuse | A key used from a new network or workload, token spikes, a new model requested | LLM10:2025 |
Send detections and summary events to the SIEM, not full content. Write detections against the security metadata so they keep working when content capture is off. For the response side, see the Prompt Injection Incident Response Playbook.
Investigation questions the logs must answer: who started the session and through which application; which model and system prompt version responded; which documents were retrieved; which tools were called with what arguments and results; what credential each tool call used; and what the user saw. If your schema cannot answer one of these, add the field before you need it.
Measuring it
- Share of LLM and agent traffic passing through a logged gateway or instrumented framework (target: all production traffic).
- Share of records with end user, agent and credential identity populated.
- Redaction test pass rate in each release (target: no seeded secret or personal data in any store).
- Records past their retention date still present (target: none).
- Content tier reads without a linked ticket (target: none).
Rolling it out
- Define the use cases and the schema: list the detections and investigation questions, then the minimum fields for each.
- Route traffic: put production calls through a gateway or instrumented SDK; block direct provider access where possible.
- Turn on metadata first: run for two to four weeks, build detections and baselines.
- Add redaction and test it: deploy secret and personal data redaction in the collector, with seeded tests.
- Add content by use case: enable redacted content for agent and tool steps, behind the separate store and access process. Complete a data protection impact assessment where personal data is involved.
- Lock and verify: apply WORM retention, integrity checks and access alerts, then run a mock investigation end to end.
- Roll back: if redaction misses a data class, stop content capture with a feature flag, purge affected records and fix the rule before re-enabling.
Framework mapping
| Framework | Reference | How it applies |
|---|---|---|
| NIST SP 800-53 Rev 5 | AU-2, AU-3, AU-12 | Which events to log and what each record contains |
| NIST SP 800-53 Rev 5 | AU-9, AU-9(4), AU-11 | Protecting logs and setting retention |
| NIST SP 800-53 Rev 5 | SI-4 | Monitoring for injection and abuse |
| NIST CSF 2.0 | PR.PS-04, DE.CM-09 | Log generation and monitoring of software and its data |
| NIST AI 600-1 | GV-1.5-003, MS-2.7-004 | Retention policy; security effectiveness metrics |
| OWASP Top 10 for LLM Applications 2025 | LLM01, LLM02, LLM06, LLM07, LLM10 | The risks the logs detect and must not themselves create |
| EU AI Act | Articles 12, 19, 26(6) | Record-keeping for high-risk systems |
Common failure patterns
- Debug logging left on: an SDK or framework logs full requests, including API keys in headers and complete prompts, to application logs that many people can read.
- No identity on agent calls: tool calls are logged under one shared service account, so nobody can tell which user or agent triggered a destructive action. See the Agent Identity and Access Guide.
- Redaction in one place only: the observability tool masks content, but a second exporter or the provider's own logging stores it unredacted.
- Content kept forever: prompts land in a general log platform with a multi-year default retention, creating a large personal data store nobody planned.
- Detections that depend on content: rules only work on full text, so they go blind when privacy review turns content capture off.
- Editable evidence: logs sit in a store the platform team can delete, so their integrity cannot be shown after an incident.
Practitioner checklist
- Write down the detection and investigation use cases before choosing fields.
- Log identity, model, token, tool and verdict metadata for every production call.
- Use OpenTelemetry GenAI attribute names and pin the convention version.
- Redact secrets and personal data centrally before the first write, and test with seeded data each release.
- Store content separately, by reference, with short retention and ticketed access.
- Publish a retention schedule per tier and check it against privacy law and the AI Act where relevant.
- Apply WORM storage, integrity checks and alerts on log access and policy changes.
- Build detections on metadata so they survive content capture being off.
- Run a mock investigation and fix any question the logs cannot answer.
Standards and references
- OWASP: Top 10 for LLM Applications 2025
- OWASP: Logging Cheat Sheet
- OpenTelemetry: GenAI semantic conventions
- NIST: AI 600-1 Generative Artificial Intelligence Profile
- NIST: SP 800-92 Rev 1 Cybersecurity Log Management Planning Guide (Initial Public Draft)
- EUR-Lex: Regulation (EU) 2024/1689 (AI Act)
- ICO: How should we assess security and data minimisation in AI?
Related NHI Mgmt Group resources: LLM Observability Guide · Amazon Bedrock Model Invocation Logging Guide · Prompt Injection Guide · Log Management and Retention Guide