Writing Audit Logging Code With LLMs in November 2026: Record Who Did What to Which Record, Make the Log Append-Only, and Keep Secrets Out

Sooner or later someone asks a question your app cannot answer: who changed this customer's plan, when was this invoice deleted, which admin turned off two-factor login for that account? An audit log is the answer. Ask an LLM to "add audit logging" and you will usually get a console.log or a logger call sprinkled into a few controllers. It looks like logging, but it fails the moment you actually need it: half the write paths are missing, the entries cannot be tied to a user, anyone with database access can edit them, and some of them contain password reset tokens.

This guide covers how to get audit logging code out of an AI coding assistant that holds up when a customer, an auditor, or your own incident review needs it. The short version: decide what an event looks like before any code exists, record it on every write path, make the log append-only, and keep secrets and unneeded personal data out of it.

A handwritten page from an 18th-century ship's logbook

A ship's log was kept entry by entry and never rewritten. Your audit trail should work the same way. Image: Page from the logbook of the Dutch warship Medea in 1786 by A.A. Buyskes, Public domain, via Wikimedia Commons.

Audit logs are not application logs

Application logs exist to help engineers debug. They are noisy, short-lived, sampled, and nobody minds if a line goes missing. Audit logs exist to answer questions about accountability. They have different rules:

  • Completeness matters more than volume. Missing one "role changed" event is worse than missing a thousand debug lines.
  • They are structured. Each event has fixed fields you can query, not free text you grep.
  • They must not be editable after the fact by the same people whose actions they record.
  • They are kept for a defined period, which is often longer than your debug logs and should be decided on purpose.

Say this explicitly in your prompt. If you ask for "logging," a model will reasonably reach for your existing logger. Ask for "an audit trail stored as structured records, separate from application logs," and you get a different and better design.

Step 1: Define the event shape before asking for code

The most useful thing you can give the model is a schema. Without one, every generated call site invents its own fields and the log becomes impossible to query. A practical starting shape:

audit_events
  id            bigint, generated
  occurred_at   timestamptz, set by the database, not the client
  actor_type    text      -- 'user', 'admin', 'api_key', 'system'
  actor_id      text      -- who did it
  on_behalf_of  text NULL -- set when an admin impersonates a user
  action        text      -- 'invoice.deleted', 'user.role_changed'
  target_type   text      -- 'invoice'
  target_id     text      -- '8812'
  tenant_id     text      -- which customer account this belongs to
  request_id    text      -- ties the event to your request logs
  ip_address    inet NULL
  changes       jsonb     -- {"role": {"from": "member", "to": "admin"}}
  metadata      jsonb     -- anything else, small

A few choices here are worth explaining to the model, because it will not guess them:

  • Use a fixed vocabulary for action. A noun-dot-verb pattern like user.role_changed keeps queries simple. Ask the model to put every allowed action in one enum or constant list, so a typo fails at build time instead of producing an event nobody can find.
  • Record the impersonator. If support staff can act as a customer, the log needs both identities. Otherwise every support action looks like the customer did it.
  • Let the database set the time. Client clocks drift and can be faked. A database default such as now() gives you one consistent clock.
  • Store a diff, not a full snapshot. Recording only the fields that changed keeps rows small and makes it much easier to keep sensitive columns out.

Step 2: List every write path, then cover all of them

Audit logs fail mostly through omission. The model adds an event to the obvious "update user" endpoint and misses the bulk import, the admin panel, the background job that expires trials, and the one-off script someone runs in production every quarter.

Before you ask for code, make a list of the actions you care about and where each one can happen. Then ask the model to help find the ones you missed:

Here is our routes file, our background job definitions, and our admin controller. List every code path that changes a user's role, email, password, two-factor settings, or billing plan, or deletes a user or invoice. For each one, give the file and function name. Do not write any code yet.

Check that list against the code yourself. Then, for the implementation, push the audit call as close to the data change as possible. A shared service function such as changeUserRole(actor, userId, newRole) that both updates the row and writes the event is far harder to bypass than an audit call in each controller. If three controllers each do their own update, ask the model to refactor them onto the shared function first.

Write the event in the same transaction

If the change and the audit event are written separately, you will eventually get one without the other: the update commits, then the process crashes before the event is written. When both live in the same database, write them in the same transaction:

async function changeUserRole(db, actor, userId, newRole) {
  await db.transaction(async (tx) => {
    const user = await tx.users.findForUpdate(userId);
    if (user.role === newRole) return;          // no-op, no event
    await tx.users.update(userId, { role: newRole });
    await tx.auditEvents.insert({
      actorType: actor.type,
      actorId: actor.id,
      onBehalfOf: actor.impersonating ?? null,
      action: 'user.role_changed',
      targetType: 'user',
      targetId: String(userId),
      tenantId: user.tenantId,
      requestId: actor.requestId,
      changes: { role: { from: user.role, to: newRole } },
    });
  });
}

Now either both rows exist or neither does. If your audit store is a separate system, such as a log service, write the event to an outbox table inside the transaction and have a worker ship it afterwards. Ask the model for that pattern by name; it knows it, but will not reach for it unless you ask.

A security camera mounted on a wall

A camera only helps if it covers every door. Audit events only help if they cover every write path. Image: Security camera around Ebisu Garden Place by Syced, CC0, via Wikimedia Commons.

Step 3: Make the log append-only

An audit log that the application can update or delete is only a suggestion. The goal is that the account your app uses can add events but cannot change or remove them. In PostgreSQL that is a few lines of permissions:

-- app_user is the role your application connects as
GRANT INSERT, SELECT ON audit_events TO app_user;
REVOKE UPDATE, DELETE, TRUNCATE ON audit_events FROM app_user;

A trigger that raises an error on UPDATE or DELETE adds a second layer that also catches mistakes made under other roles. It does not stop a database superuser, so do not describe it as tamper-proof. For stronger guarantees, copy events regularly to storage the application account cannot write to after the fact, such as a separate account or a bucket with object locking turned on.

Watch for generated code that quietly breaks this rule. Models often add an updated_at column, an "edit event" admin action, or a cleanup job that deletes old rows using the app's own credentials. Retention cleanup is legitimate, but it should run under a separate role with its own permissions, not the one serving web traffic.

Step 4: Keep secrets and unneeded personal data out

The fastest way to make an audit log a liability is to dump whole request bodies or whole database rows into it. That is exactly what a model tends to do when asked to "log the change." You end up storing password hashes, API keys, reset tokens, and full card or ID numbers in a table that is kept for years and read by support staff.

Give the model concrete rules:

  • Use an allowlist of fields per action, not a blocklist. A blocklist misses the new recovery_code column someone adds next month.
  • For secret fields, record that they changed, not the value: {"password": "changed"}.
  • Do not log raw tokens or keys. If you need to tell which API key acted, log its id or a short non-secret prefix.
  • Decide how long you keep events and which personal fields they hold. Privacy rules in many places expect you to justify what you keep and for how long; check with whoever owns compliance for your product.

Then add a test that fails if any audit event contains a known secret. Create a user with a distinctive password and token in the test, run the flows, and assert that neither string appears anywhere in the serialized events.

Step 5: Test the log like a feature

Audit logging rarely has tests, which is why it rots. Ask the model for tests along these lines:

  1. Each audited action writes exactly one event with the expected action, actor, and target.
  2. A no-op change writes no event. Setting the role to the role it already has should not create noise.
  3. A failed change writes no event. If the update throws or is rejected by an authorization check, the transaction rolls back and the log stays clean. If you also want to record denied attempts, make that a separate, deliberate action such as user.role_change_denied.
  4. Impersonation records both identities.
  5. The app's database role cannot update or delete events. Connect as that role in the test and assert the statement is refused.
  6. No secrets appear in events, as described above.

A cheap coverage check helps too: keep the list of required actions in one place, and have a test that fails if any action in the list was never emitted by the test suite. New actions then need a test before they count as done.

Step 6: Make it readable for the people who need it

The log only pays off if someone can use it. Ask the model for one simple query or admin view: filter by target ("everything that happened to invoice 8812"), by actor ("everything this admin did last week"), and by tenant. Add indexes for those filters, for example on (tenant_id, occurred_at) and (target_type, target_id). If customers will see their own audit trail, make sure the view is scoped to their tenant, and test it as a user from a different tenant.

A prompt that tends to work

Add an audit trail to this service. Store events in a new audit_events table using the schema below, separate from application logs. Write each event in the same database transaction as the change it records, through shared service functions rather than in each controller. Use a fixed list of action names. Record actor, impersonator if any, target, tenant, request id, and a diff of only the allowed fields for each action; never store passwords, tokens, or keys, only that they changed. The app's database role must be able to insert and read events but not update or delete them. Include tests for: one event per change, no event on no-op or failed changes, impersonation, refused updates and deletes, and no secrets in events. Here is the schema, the list of actions, and the relevant files.

Checklist before you merge

  • Every action on your list has a code path that writes an event, and you checked the list against the code yourself.
  • Events are written in the same transaction as the change, or through an outbox.
  • Action names come from one fixed list.
  • The application's database role cannot update, delete, or truncate audit events.
  • Secret fields are recorded as "changed," never by value, and a test proves it.
  • Retention is decided and cleanup runs under a separate role.
  • Support and customers can filter the log by target, actor, and tenant, and tenant scoping is tested.

An LLM can write nearly all of this quickly. What it cannot do is decide which actions matter to your business, find the script someone runs by hand every quarter, or know which columns are secret. Give it those answers up front, and review the result as if you were the person who will one day need to prove what happened.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Tencent Hy4 Preview: Open 770B MoE Built for Real Work

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)