Join our Newsletter — 33% off our NHI Course
Home› Guides› LLM Logging Guide: What to Capture, Redact and…
Guide LLM & GenAI Security

LLM Logging Guide: What to Capture, Redact and Retain for Security

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 14 min read
On this page

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.

FieldOpenTelemetry attributeWhy security needs itDefault
Timestamp, trace and span IDStandard span fieldsOrdering events and joining model, tool and retrieval stepsAlways
End user identity (pseudonymous ID)None in GenAI set: use your own user or enduser attributeWho initiated the requestAlways
Calling application, agent and versiongen_ai.agent.id, gen_ai.agent.name, gen_ai.agent.versionWhich workload acted, and whether it changedAlways
Credential used (key ID or service principal, never the secret)None in GenAI setDetecting stolen or misused API keys and tokensAlways
Provider, requested and actual modelgen_ai.provider.name, gen_ai.request.model, gen_ai.response.modelUnapproved model use, unexpected fallbackAlways
Operation and conversationgen_ai.operation.name, gen_ai.conversation.idRebuilding a multi-turn attackAlways
Token countsgen_ai.usage.input_tokens, gen_ai.usage.output_tokensAbuse, extraction and runaway cost (LLM10:2025 Unbounded Consumption)Always
Finish reason and response statusgen_ai.response.finish_reasonsContent filter hits, truncation, refusalsAlways
Guardrail and classifier verdictsCustom attributesInjection, jailbreak and data loss signalsAlways
Tool name, type and call IDgen_ai.tool.name, gen_ai.tool.type, gen_ai.tool.call.idWhat the agent didAlways
Tool call arguments and resultgen_ai.tool.call.arguments, gen_ai.tool.call.result (Opt-In)Which records, files or commands were touchedArguments: redacted, usually yes. Results: by use case
Retrieval source IDsgen_ai.data_source.idTracing indirect injection to the poisoned documentAlways (IDs, not text)
System prompt versiongen_ai.prompt.name, gen_ai.prompt.versionProving which instructions were liveAlways (version, not text)
Input and output messagesgen_ai.input.messages, gen_ai.output.messages (Opt-In), or the _ref variantsInvestigating what was asked and answeredBy use case, redacted, short retention
System instructions and tool definitionsgen_ai.system_instructions, gen_ai.tool.definitions (Opt-In)Detecting tampered prompts or tool listsStore 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.

  1. 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.
  2. 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.
  3. 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.
  4. Redact once, centrally: do it in the gateway or the telemetry collector, not in one SDK, so every exporter receives the same cleaned data.
  5. 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.
  6. 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 tierContentsExample retentionWho can read
Security metadataIdentity, model, tokens, tool names, verdicts, source IDs12 months, or your security log standardSOC, platform engineers
Redacted contentPrompts, responses, tool arguments after redaction30 days or less unless held for a caseNamed investigators, on a ticket
Re-identification dataToken map or encrypted originalsShortest period that supports investigationsDual approval only
Legal holdRecords tied to an incident or disputeUntil the hold is releasedIncident 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 caseSignals in the logReference
Direct prompt injection and jailbreak attemptsGuardrail verdict spikes per user or key, repeated refusals followed by a success, unusual system prompt override phrasingLLM01:2025, ATLAS AML.T0051, AML.T0054
Indirect prompt injectionTool calls or data access that follow retrieval of an external document in the same trace; new retrieval source IDs before a sensitive tool callLLM01:2025, AML.T0051
Excessive agencyTool calls outside the agent's normal set, write or delete operations at unusual volume, calls on behalf of users who never askedLLM06:2025
Sensitive data exposureRedaction counts on outputs, very long outputs to one caller, retrieval of restricted sourcesLLM02:2025
System prompt extractionOutputs matching the stored system prompt hash or fragmentsLLM07:2025
Stolen keys and abuseA key used from a new network or workload, token spikes, a new model requestedLLM10: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

  1. Define the use cases and the schema: list the detections and investigation questions, then the minimum fields for each.
  2. Route traffic: put production calls through a gateway or instrumented SDK; block direct provider access where possible.
  3. Turn on metadata first: run for two to four weeks, build detections and baselines.
  4. Add redaction and test it: deploy secret and personal data redaction in the collector, with seeded tests.
  5. 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.
  6. Lock and verify: apply WORM retention, integrity checks and access alerts, then run a mock investigation end to end.
  7. 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

FrameworkReferenceHow it applies
NIST SP 800-53 Rev 5AU-2, AU-3, AU-12Which events to log and what each record contains
NIST SP 800-53 Rev 5AU-9, AU-9(4), AU-11Protecting logs and setting retention
NIST SP 800-53 Rev 5SI-4Monitoring for injection and abuse
NIST CSF 2.0PR.PS-04, DE.CM-09Log generation and monitoring of software and its data
NIST AI 600-1GV-1.5-003, MS-2.7-004Retention policy; security effectiveness metrics
OWASP Top 10 for LLM Applications 2025LLM01, LLM02, LLM06, LLM07, LLM10The risks the logs detect and must not themselves create
EU AI ActArticles 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

Related NHI Mgmt Group resources: LLM Observability Guide · Amazon Bedrock Model Invocation Logging Guide · Prompt Injection Guide · Log Management and Retention Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.