# Audit trail: what to record, how to protect it and what the rules say

> An audit trail, or audit log, is a protected record of who did what to which data, when and with what result. What to record, how to protect it and the rules.

- URL: https://computese.com/audit-trail/
- Author: Kai Mai, Chief Technology Officer, Computese
- Published: 2026-11-28
- Updated: 2026-12-03
- Topics: Custom software, Security

## In short
- An audit trail records who did what to which data, when, from where and with what result, in an order that lets you reconstruct a sequence of events. Unlike an application log, it is kept, protected and reviewed on purpose.
- Record the actor, action, target, UTC time, source, outcome and the changed record before and after. Keep secrets and unneeded personal data out, and write each entry in the same database transaction as the change it records.
- Permissions and triggers stop mistakes and the application's own account, not the table owner. A hash chain shows edits only if the latest hash is also kept where the database owner cannot reach it.
- No rule says 'keep an audit trail' in one place. PCI DSS asks for at least 12 months, with the latest 3 months immediately available. HIPAA sets no period for logs, and GDPR does not use the words audit trail.
- NIST SP 800-92 (2006) is still the final log management guide as of December 2026. Its revision, a planning guide, has been an initial public draft since October 2023.

An audit trail, also called an audit log, is a chronological, protected record of who did what to which data, when, from where and with what result, kept so the events behind a change can be reconstructed. It is built for accountability and investigation, not debugging, so it records every action that matters and resists edits.

This guide is for developers, product owners and anyone who must answer an auditor, a customer or a regulator. It covers what an entry holds, which rules require a trail, how to make it tamper-evident, what never to log, and how to write, keep, review and alert on it. Rules and products are described as of December 2026, the SQL ran on PostgreSQL 19.0, and the examples come from three sites we build and run.

## What is an audit trail, and how is it different from an audit log?

NIST's glossary in [SP 800-53 Rev. 5](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-53r5.pdf) defines the pieces. An audit log is a chronological record of system activities, and an audit record is one entry in it. An audit trail reconstructs the sequence of activities leading to a specific operation or event, from inception to result. The words overlap in practice: [pgAudit](https://github.com/pgaudit/pgaudit) says what it collects is "properly called an audit trail or audit log". The working distinction is that the log is the store and the trail is the ordered set of records that tells the story of one operation.

The [OWASP Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html) says audit and transaction logs usually serve different purposes than security event logs and often should be kept separate. An application produces several records, and each answers a different question. Our [observability guide](https://computese.com/observability/) covers the logs, metrics and traces.

| Question                                                             | Record that answers it | What it is kept for                                                   |
| -------------------------------------------------------------------- | ---------------------- | --------------------------------------------------------------------- |
| Why did this request fail?                                           | Application log        | Debugging, baselines and performance                                  |
| How many requests failed this hour?                                  | Metric                 | Counts and timings aggregated over time; they cannot say who did what |
| How did this order reach its current state?                          | Event store            | Rebuilding state from the sequence of changes                         |
| Who changed this price, from what to what, and were they allowed to? | Audit trail            | Accountability and investigation                                      |

![One server on the left sends four arrows to four stores: a scroll of grey lines, a small bar chart, a stack of linked cards and an orange ledger book fastened with a padlock.](https://computese.com/images/blog/audit-trail/audit-trail-vs-logs.15ffd95f70-1536.webp)

*One application produces several records, and only the trail is kept to answer who did what.*

[Event sourcing](https://martinfowler.com/eaaDev/EventSourcing.html) is the closest relative. Martin Fowler's 2005 description stores every change to application state as an event so past states can be rebuilt. He notes that when the current state is held in a database, the event logs may be there only for audit and special processing. Such a store usually holds accepted changes, not refused attempts, reads or administrator actions. Our [event-driven architecture guide](https://computese.com/event-driven-architecture/) covers event streams.

## What should every audit record contain?

NIST's control AU-3, in [SP 800-53 Rev. 5](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-53r5.pdf), asks each record to establish the type of event, when, where, its source, its outcome and the identity of anyone or anything involved. PCI DSS requirement 10.2.2, as [Microsoft Learn reproduces it](https://learn.microsoft.com/en-us/entra/standards/pci-requirement-10), asks for much the same, including the affected resource. OWASP reduces both to ["when, where, who and what"](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html).

For a business application that becomes seven fields:

| Field            | What to store                                   | Notes                                                               |
| ---------------- | ----------------------------------------------- | ------------------------------------------------------------------- |
| Actor            | A stable account id, the role, person or system | An id, not a display name: names change                             |
| Action           | A fixed name such as `account.plan_change`      | A short vocabulary you can search and alert on                      |
| Target           | The type and id of what was acted on            | For reads and exports, the scope and filters                        |
| Time             | UTC, to the microsecond                         | NIST's AU-8 allows UTC or a stored offset                           |
| Source           | The client address and the interface used       | OWASP lists the address under "who" and the interface under "where" |
| Outcome          | `success`, `failure` or `denied`, with a reason | PCI DSS 10.2.1.4: invalid logical access attempts                   |
| Before and after | The affected record, whole                      | Secrets stay out; see below                                         |

![A tall card of seven rows, each with a small symbol and a grey bar: a badge, a gear, a box, a clock, a router, a check mark in a circle and two overlapping pages drawn in orange.](https://computese.com/images/blog/audit-trail/audit-record-fields.566e1d9b40-1536.webp)

*A fixed set of fields turns a change into evidence that someone can search.*

Here is one entry, an audit trail example for a plan change:

```json
{
  "seq": 1,
  "occurred_at": "2026-12-03T14:07:22.481516Z",
  "actor_id": "user:42",
  "action": "account.plan_change",
  "target_type": "account",
  "target_id": "1",
  "outcome": "success",
  "source_ip": "203.0.113.7",
  "before": { "plan": "basic" },
  "after": { "plan": "pro" }
}
```

A refused attempt has the same shape, with `outcome` set to `denied` and no before or after.

[Via Ottawa](https://viaottawa.ca/), a guide to local businesses across Ottawa that we build and run, stores the before and after of each administrator change to a listing whole, not as a diff. A diff only reads against the version it was computed from, and the change overwrote that version. The rows later found a second use. When the team ruled that a seed job or migration must never overwrite a listing a person had edited, a migration backfilled an edited-by-a-person marker from the audit rows and other records of human changes.

## Which rules require an audit trail, and what do they say?

No single rule says "keep an audit trail" and stops. Each asks for records of activity, protection and review in its own words, and most leave the period open.

| Rule                           | What it asks for                                                                          | Retention it sets                                             |
| ------------------------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
| PCI DSS v4.0.1, requirement 10 | Audit logs on all components and cardholder data, protected and reviewed daily            | At least 12 months, the latest 3 months immediately available |
| HIPAA, 45 CFR 164.312(b)       | Mechanisms that record and examine activity in systems with electronic health information | None for logs; six years for required documentation           |
| 21 CFR 11.10(e), FDA           | Secure, time-stamped audit trails of changes to electronic records                        | As long as the records they cover                             |
| SOC 2                          | An auditor's report against the AICPA Trust Services Criteria                             | Ask your auditor                                              |
| GDPR                           | No audit-trail wording; security, accountability, storage limitation                      | No longer than necessary                                      |
| PIPEDA, Schedule 1             | No audit-log wording; safeguards and retention guidelines                                 | Your own minimum and maximum                                  |
| Ontario PHIPA, section 10.1    | An electronic audit log; not yet in force                                                 | Not stated                                                    |

### PCI DSS v4.0.1

The PCI Security Standards Council's [document library](https://www.pcisecuritystandards.org/document_library/?category=pcidss&document=pci_dss) lists v4.0.1, published in June 2024, as the standard as of December 2026. Its [announcement](https://blog.pcisecuritystandards.org/just-published-pci-dss-v4-0-1) calls it a limited revision with no added or deleted requirements and says v4.0 retired on 31 December 2024. The standard sits behind a licence agreement, so the wording below follows the Microsoft Learn copy of v4.0's requirement 10, last updated in October 2023, before v4.0.1 existed.

Requirements 10.2.1.1 to 10.2.1.7 name what the logs must capture: access to cardholder data, administrator actions, access to the logs, invalid access attempts, credential changes, the logs starting or stopping, and creation or deletion of system-level objects. Requirement 10.3 protects them with job-based read access, protection from modification, prompt backup to a central server or hard-to-modify media, and change detection that alerts. Requirement 10.4.1 sets daily review, 10.4.1.1 requires automation, and 10.5.1 requires at least 12 months of history, the latest three months immediately available.

### HIPAA and the FDA

HIPAA's Security Rule requires audit controls. [Section 164.312(b)](https://www.ecfr.gov/current/title-45/subtitle-A/subchapter-C/part-164/subpart-C/section-164.312) asks for mechanisms that record and examine activity in systems that contain or use electronic protected health information, and [section 164.308(a)(1)(ii)(D)](https://www.ecfr.gov/current/title-45/subtitle-A/subchapter-C/part-164/subpart-C/section-164.308) requires regular review of audit logs and access reports. Neither sets a retention period for logs. [Section 164.316(b)(2)(i)](https://www.ecfr.gov/current/title-45/subtitle-A/subchapter-C/part-164/subpart-C/section-164.316) requires six years for the documentation the rule requires.

The FDA is more specific. [21 CFR 11.10(e)](https://www.ecfr.gov/current/title-21/part-11) asks for secure, computer-generated, time-stamped audit trails of operator entries and actions that create, modify or delete electronic records. Changes must not obscure earlier entries, and the trail is kept at least as long as the records it covers. Part 11 applies to records kept under FDA requirements or submitted to the agency.

### SOC 2

SOC 2 is an auditor's report on your controls against the AICPA's [Trust Services Criteria](https://www.aicpa-cima.com/resources/download/2017-trust-services-criteria-with-revised-points-of-focus-2022), not a rule. The criteria text sits behind a free AICPA account, so this guide does not quote it. Ask your auditor which trails they will sample, and keep evidence of how each is protected and reviewed.

### GDPR, PIPEDA and Ontario's PHIPA

The GDPR does not use the words audit trail or audit log. [Regulation 2016/679](https://publications.europa.eu/resource/cellar/3e485e15-11bd-11e6-ba9a-01aa75ed71a1.0006.03/DOC_1) sets principles a trail must meet because it holds personal data: kept no longer than necessary (Article 5(1)(e)), protected by appropriate security (Articles 5(1)(f) and 32), and demonstrable by the controller (Article 5(2)). Under Article 17(3), an erasure request does not override processing necessary for a legal obligation or legal claims, so name the purpose of your retention rule.

Canada's [PIPEDA](https://laws-lois.justice.gc.ca/eng/acts/p-8.6/FullText.html) has no audit-log wording either. Clause 4.5.2 of Schedule 1 asks for retention guidelines with minimum and maximum periods, and clause 4.7 for safeguards against loss, theft and unauthorized access or modification. Ontario's [PHIPA](https://www.ontario.ca/laws/statute/04p03) goes further on paper: section 10.1, added in 2020, would require custodians using electronic means to keep an electronic audit log, but as of 27 November 2026 it awaits proclamation and is not in force.

## What is the status of NIST SP 800-92 in December 2026?

NIST's [SP 800-92](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-92.pdf), the Guide to Computer Security Log Management, was published in September 2006 and is still final as of December 2026. Its revision, [SP 800-92 Rev. 1](https://csrc.nist.gov/pubs/sp/800/92/r1/ipd), the Cybersecurity Log Management Planning Guide, was released as an initial public draft on 11 October 2023, and comments closed on 29 November 2023. NIST's [log management project page](https://csrc.nist.gov/projects/log-management), updated on 20 November 2025, says NIST is addressing those comments and that the new document replaces the original. Its scope is planning, not implementing log management technology.

The controls that call for a trail live in SP 800-53 Rev. 5, whose [publication page](https://csrc.nist.gov/pubs/sp/800/53/r5/upd1/final) lists a minor Release 5.2.0 of 27 August 2025.

## How do you make an audit trail tamper-evident?

Tamper-evident means an edit is detected, not that it cannot happen. [RFC 9162](https://www.rfc-editor.org/rfc/rfc9162.html) says this of certificate logs: they do not prevent misissuance but let interested parties detect it. Schneier and Kelsey's [paper on secure audit logs](https://www.schneier.com/wp-content/uploads/2016/02/paper-auditlogs.pdf) describes detecting manipulation after the fact, and notes that nothing can protect entries written after an attacker takes over the machine. So treat "immutable" as a goal that layers approach. NIST's control AU-9(4) says why: people with privileged access who are also the subject of an audit can inhibit audit activities or modify records.

| Layer                                            | Stops                                                         | Does not stop                                                 |
| ------------------------------------------------ | ------------------------------------------------------------- | ------------------------------------------------------------- |
| Insert-only database role                        | The application's own bugs and stolen application credentials | The table owner, superusers, anyone who changes grants        |
| Triggers that refuse UPDATE, DELETE and TRUNCATE | A role that holds the privilege using it by mistake           | The owner, who can disable them                               |
| Hash chain                                       | Unnoticed edits to past rows, once the chain is checked       | An owner who recomputes every hash, or drops the newest rows  |
| Copy of the latest hash elsewhere                | The recomputation                                             | Anyone who also controls the copy                             |
| Write-once storage, separate account             | Deletion and overwriting until retention ends                 | False entries written before locking, and closing the account |

### Take away the write permissions

OWASP recommends a separate database account used only for writing log data, with restrictive permissions. Give the application's role INSERT on the audit table, SELECT because the chain trigger below reads the last row as that role, and nothing else. Add triggers that refuse UPDATE, DELETE and TRUNCATE in case a role ever holds those privileges; per the [CREATE TRIGGER documentation](https://www.postgresql.org/docs/current/sql-createtrigger.html), a TRUNCATE trigger can only be statement-level, so it needs its own. Mark both ENABLE ALWAYS, because per the [ALTER TABLE documentation](https://www.postgresql.org/docs/current/sql-altertable.html) a default trigger does not fire in a session whose replication role is replica.

```sql
CREATE TABLE audit_log (
  seq         bigint      PRIMARY KEY,
  occurred_at timestamptz NOT NULL,
  actor_id    text        NOT NULL,
  action      text        NOT NULL,
  target_type text        NOT NULL,
  target_id   text        NOT NULL,
  outcome     text        NOT NULL CHECK (outcome IN ('success', 'failure', 'denied')),
  source_ip   inet,
  before      jsonb,
  after       jsonb,
  prev_hash   text        NOT NULL,
  row_hash    text        NOT NULL
);

CREATE FUNCTION audit_log_refuse() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  RAISE EXCEPTION 'audit_log is append-only: % refused', TG_OP;
END $$;

CREATE TRIGGER audit_log_no_edit BEFORE UPDATE OR DELETE ON audit_log
  FOR EACH ROW EXECUTE FUNCTION audit_log_refuse();
CREATE TRIGGER audit_log_no_truncate BEFORE TRUNCATE ON audit_log
  FOR EACH STATEMENT EXECUTE FUNCTION audit_log_refuse();
ALTER TABLE audit_log ENABLE ALWAYS TRIGGER audit_log_no_edit;
ALTER TABLE audit_log ENABLE ALWAYS TRIGGER audit_log_no_truncate;

REVOKE ALL ON audit_log FROM PUBLIC;
GRANT INSERT, SELECT ON audit_log TO app_role;
```

In the test, the application role's UPDATE, DELETE and TRUNCATE failed with `permission denied for table audit_log`, and the owner's failed with the trigger's message. Then the owner disabled the trigger, which PostgreSQL allows whoever owns the table, edited a row and switched it back on. This layer keeps the application honest, not the table owner.

![A server and laptop on the left push sealed envelopes toward a tall wall with one narrow orange slot. Beyond the wall, a separate small building holds a padlocked chest, and no arrow leads back.](https://computese.com/images/blog/audit-trail/append-only-slot.4cbace92d7-1536.webp)

*The application can drop entries through the slot but cannot reach back, and the chest sits outside its own account.*

### Chain the rows with hashes

Each row stores the hash of the row before it and a hash over its own fields. Change an old row and its hash stops matching; delete a middle row or reorder rows and a link breaks, though deleting the newest rows breaks nothing. A BEFORE INSERT trigger fills in the chain columns, so the application cannot supply its own, and an advisory lock makes writers take turns so two inserts cannot link to the same predecessor. Audited writes queue behind each other.

```sql
CREATE FUNCTION audit_row_hash(r audit_log) RETURNS text LANGUAGE sql AS $$
  SELECT encode(sha256(convert_to(jsonb_build_array(
    r.seq, to_char(r.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'),
    r.actor_id, r.action, r.target_type, r.target_id, r.outcome, host(r.source_ip),
    r.before, r.after, r.prev_hash)::text, 'UTF8')), 'hex')
$$;

CREATE FUNCTION audit_log_chain() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE last_row audit_log;
BEGIN
  PERFORM pg_advisory_xact_lock(hashtext('audit_log'));
  SELECT * INTO last_row FROM audit_log ORDER BY seq DESC LIMIT 1;
  NEW.seq         := COALESCE(last_row.seq, 0) + 1;
  NEW.occurred_at := clock_timestamp();
  NEW.prev_hash   := COALESCE(last_row.row_hash, repeat('0', 64));
  NEW.row_hash    := audit_row_hash(NEW);
  RETURN NEW;
END $$;

CREATE TRIGGER audit_log_chain BEFORE INSERT ON audit_log
  FOR EACH ROW EXECUTE FUNCTION audit_log_chain();

CREATE VIEW audit_chain_check AS
SELECT seq,
       row_hash  = audit_row_hash(a) AS hash_ok,
       prev_hash = COALESCE(lag(row_hash) OVER (ORDER BY seq), repeat('0', 64)) AS link_ok
FROM audit_log a;
```

After the owner edited row 1, this query named it as the first broken row: its contents no longer match its hash, though its link still holds.

```sql
SELECT seq, hash_ok, link_ok FROM audit_chain_check
WHERE NOT (hash_ok AND link_ok) ORDER BY seq LIMIT 1;
```

```text
 seq | hash_ok | link_ok
-----+---------+---------
   1 | f       | t
```

[Minute Notary](https://minutenotary.ca/), an online notary platform we build and run, keeps a hash chain of its sealed documents. Each one adds an entry to a single chain, linked to the previous entry's hash. Appends take a lock so two documents sealed at once cannot fork the chain. Sealing also requires a trusted timestamp from an outside time-stamping authority, and fails if none is granted. The design record rejected a chain per booking: an attacker could rewrite a short chain in isolation.

### Keep a copy of the latest hash somewhere else

The chain proves the log is consistent with itself, not that it is the log you wrote. In the test the owner rewrote row 1, recomputed every later hash and put the trigger back. The chain check passed on every row. Only the latest hash, saved before the edit (in a session variable for the test, somewhere the database owner cannot write in production), no longer matched.

> [!IMPORTANT]
> A hash chain is only as strong as the place its latest hash is kept. If the database owner can edit both the table and the copy, it proves nothing.

Microsoft's [ledger feature for SQL Server](https://learn.microsoft.com/en-us/sql/relational-databases/security/ledger/ledger-overview) states the dependency: it stores database digests outside the database in tamper-proof storage, because an attacker who could modify them could change the data, regenerate the hashes and rewrite the digests. [NIST SP 800-92](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-92.pdf) likewise says original digests should be protected from alteration by FIPS-approved encryption, read-only media or other suitable means. So after each batch, copy the latest sequence number and hash to a system the database owner does not control, such as a bucket in a separate account with an object lock. An [RFC 3161](https://www.rfc-editor.org/rfc/rfc3161.html) time-stamping authority can also sign the hash.

![Five document cards in a row, each linked to the next by an arrow from its round seal. The middle card has a torn corner outlined in orange, and a dashed arrow copies the last seal into a padlocked safe below.](https://computese.com/images/blog/audit-trail/hash-chain-copy.388e931cfc-1536.webp)

*Editing one card breaks every seal after it, and the copy kept outside shows whether someone re-sealed them.*

Verifying a hash chain means reading every event between snapshots, as Crosby and Wallach note in [their USENIX Security paper](https://www.usenix.org/legacy/event/sec09/tech/full_papers/crosby.pdf), which proposes a tree with logarithmic proofs for outside verifiers.

### Move closed periods to write-once storage

Object Lock, described in the [Amazon S3 User Guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html), is WORM storage: a write-once-read-many model. In compliance mode no user, including the account's root user, can overwrite or delete a protected version or shorten its retention. The only way to delete one early is to delete the AWS account; governance mode lets users with special permissions override. A legal hold stays until someone removes it. Object Lock needs versioning enabled, and it locks what you wrote, so the entry must already be correct.

## What should an audit trail never contain?

Anything you could not defend if it leaked. OWASP's Logging Cheat Sheet lists what should be removed, masked, sanitized, hashed or encrypted rather than logged: access tokens, session identifiers, passwords, connection strings, encryption keys, payment card and bank account data, sensitive personal data, and information it is illegal to collect. OWASP's [A09:2025](https://owasp.org/Top10/2025/A09_2025-Security_Logging_and_Alerting_Failures/) counts logging such information among the failures.

> [!WARNING]
> In an append-only table, a secret written once is hard to take back. Keep tokens, passwords, keys and card numbers out of the entry by construction, not by cleanup.

Three habits keep them out:

1. **Snapshot an allowlist of fields** per record type, so a new column does not enter the trail by default, and record that something happened, not what it held: an export's filters and row count, not the file.
2. **Reject secret-shaped keys at the writer.** One function writes every entry and refuses names that look like secrets.
3. **Treat attacker-influenced values as untrusted,** or log injection can forge entries. OWASP advises structured formats such as JSON, since line breaks in unstructured text enable it, and a size limit on user input.

[Good Cleaner Co.](https://goodcleaner.ca/), a local cleaning company serving Ottawa homes and businesses whose site we build and run, enforces the second habit in code: the function that writes an audit event refuses metadata whose keys look like secrets. A sign-in ticket's event carries the row id and the account, never the ticket or its digest, because possessing the ticket is the whole secret. The admin screen shows an event's details only if they match the schema for its type. Our [secure coding checklist](https://computese.com/best-practices-for-secure-coding/) covers the wider habit.

## How do you write the entry so it matches the change?

Write it in the same transaction as the change. Saving a record and then writing its audit entry in a second call is a dual write, and either half can fail alone; AWS's [transactional outbox guidance](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html) describes the same problem for messages. A crash between the two leaves a change nobody can account for, while one transaction commits both or neither.

![Top row: a laptop sends a table and a ledger page, inside one dashed boundary, to a database along an arrow with an orange check mark. Bottom row: the boundary is turned back and the database stays empty.](https://computese.com/images/blog/audit-trail/same-transaction.424c5035b0-1536.webp)

*The entry commits with the change, or neither does.*

In the test, a plan change and its entry committed together, and a rolled-back transaction left neither. That suits success entries, not refusals: a denied attempt has no change to commit with, so write it in its own transaction, or the rollback that rejects the request takes the evidence with it.

### Let the database capture it, and tell it who is acting

The application knows the user, the role and the business meaning, and OWASP calls the application code the primary event data source. A trigger fires for every update, however it is run, including scripts run by hand, but it sees rows, not people, so the application hands it the actor with PostgreSQL's [SET LOCAL](https://www.postgresql.org/docs/current/sql-set.html), whose value lasts only until the end of the transaction.

```sql
CREATE FUNCTION accounts_audit() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE actor text := nullif(current_setting('app.actor_id', true), '');
BEGIN
  IF actor IS NULL THEN
    RAISE EXCEPTION 'no actor set for this transaction';
  END IF;
  INSERT INTO audit_log (actor_id, action, target_type, target_id, outcome, source_ip, before, after)
  VALUES (actor, 'account.' || lower(TG_OP), 'account', NEW.id::text, 'success',
          nullif(current_setting('app.source_ip', true), '')::inet,
          to_jsonb(OLD), to_jsonb(NEW));
  RETURN NEW;
END $$;

CREATE TRIGGER accounts_audit AFTER UPDATE ON accounts
  FOR EACH ROW EXECUTE FUNCTION accounts_audit();

BEGIN;
SET LOCAL app.actor_id = 'user:42';
SET LOCAL app.source_ip = '203.0.113.7';
UPDATE accounts SET plan = 'enterprise' WHERE id = 1;
COMMIT;
```

With the actor set, the update wrote an entry for `user:42` with the source address and the row before and after as JSON. `to_jsonb` copies every column, so on a real table list the allowed columns instead. With no actor, it raised `no actor set for this transaction` and nothing was written: a change nobody can attribute does not happen. `SET LOCAL` does not take a bind parameter, so application code should call `set_config('app.actor_id', $1, true)` instead.

### Send it elsewhere without losing entries

If the trail must also reach another system, such as the hash copy or a monitoring tool, do not call both from the application. AWS names two ways to publish reliably: an outbox table written in the same transaction and read by a relay, or [change data capture](https://computese.com/change-data-capture/). A relay can publish a message twice, so give each entry a stable key and have the receiver track what it has processed. We put a delivery that keeps failing in a [dead letter queue](https://computese.com/dead-letter-queue/) with an alert.

### Decide what happens when the write fails

Decide per event class. OWASP's cheat sheet says logging failures should not stop the application, which suits debugging output. For an entry that is the only record of a sensitive act, choose the opposite: no entry, no act. OWASP's A09 says to roll back transactions that error and always fail closed, and NIST's AU-5 lists shutting down the system among the responses an organization may define.

On Good Cleaner Co., cancelling a paid booking writes the booking change, the audit event, the refund record and the customer's queued email in one transaction. The audit event stores what the cancellation policy would have refunded next to what the office actually refunded, so an override is visible. Minute Notary is stricter about reads: a bulk export of its notary register writes its audit entry before any data leaves the server, and if that write fails, the export is refused. Its entry holds the filters and the row count, never the search term, which can be a signer's name.

## How long should audit logs be kept, and who may read them?

Keep them as long as the rules that apply to you require, and no longer. OWASP says log data must not be destroyed before the required retention period or kept beyond it. NIST's AU-11 says to retain records until they are no longer needed for administrative, legal, audit or other operational purposes, and AU-11(1) adds that long-term records must remain retrievable. GDPR's storage limitation and PIPEDA's clause 4.5 pull the other way, so write the period down with its reason.

SP 800-92 separates retention, archiving logs regularly as part of normal operations, from preservation, keeping logs that would normally be discarded because they record activity of particular interest. Object Lock's legal hold is the storage form of preservation. A workable shape is two tiers: a recent window that stays searchable, which fits PCI DSS's three months immediately available, and a locked archive whose delete step skips anything under a hold.

Reading the trail is itself an event. PCI DSS 10.2.1.3 captures all access to the audit logs, and 10.3.1 limits read access to those with a job-related need. OWASP asks that all access be recorded and monitored, and that read privileges be restricted and reviewed periodically.

## How do you review an audit trail and alert on it?

A trail nobody reads is storage. Crosby and Wallach state it plainly: tamper-evidence requires auditing, because a log nobody examines cannot reveal tampering. The rules agree: PCI DSS 10.4.1 requires daily review of security events and of critical components' logs, with 10.4.1.1 requiring automation, and HIPAA requires regular review of audit logs and access reports.

OWASP's A09:2025 stresses alerting. Its example is a children's health plan provider's website with no monitoring or logging. An attacker accessed and modified records of more than 3.5 million children, and the breach could have been under way for more than seven years.

![A stack of small cards slides into a funnel with a gear and a sieve inside. Only three cards come out along an arrow, and the last one touches a small orange bell.](https://computese.com/images/blog/audit-trail/review-and-alert.9a00f593ed-1536.webp)

*Few entries are ever read by a person, so rules and alerts decide which ones get attention.*

Start with a short list of alerts that are cheap and precise:

- **A burst of refused or failed attempts** on one account or source; our [rate limiting guide](https://computese.com/rate-limiting/) covers what to count per key.
- **Administrator actions and bulk exports** outside a change window.
- **Any read of the trail** by someone outside the allowed roles.
- **The audit logging stopping or failing,** which PCI DSS 10.2.1.6 and 10.7.2 and NIST's AU-5 address.
- **A failed chain check,** or a stored hash that no longer matches the copy.
- **A honeytoken:** OWASP suggests decoy records or identities that normal business never touches, so any access can be alerted with nearly no false positives.

## What is a sensible order to build it in?

1. **List the actions that need a trail:** administrator actions, changes to money and permissions, exports, sign-in outcomes and the trail's own settings.
2. **Fix the entry shape and action names** before writing code, and check them against AU-3 and PCI DSS 10.2.2.
3. **Create the table, the insert-only role and the triggers,** and write each entry in the same transaction as its change.
4. **Add the hash chain, a scheduled check and an outside copy** of the latest hash.
5. **Write down retention and who may read,** and record every read.
6. **Review, alert and test it like an attacker.** OWASP counts penetration tests that trigger no alert as a failure in itself.

To have the trail built in, our [custom software development service](https://computese.com/services/custom-software-development/) builds portals, admin consoles and back ends with roles, two-factor sign-in and an audit trail, plus a transactional outbox for messages that must follow a change. To test an existing trail, our [security testing service](https://computese.com/services/security-testing/) tests web apps and APIs against the OWASP Web Security Testing Guide, and its cloud configuration review checks that logging and guardrails are in place.

## Key terms
- **Audit trail**: A chronological record that reconstructs the sequence of activities leading to a specific operation or event, from start to result. The terms audit trail and audit log are often used for the same thing.
- **Audit record**: One entry in an audit log, describing a single audited event: what happened, when, where, from what source, with what outcome and to whom or what.
- **Append-only**: A table or store that accepts new rows and refuses updates and deletes. In a database it is enforced with permissions and triggers, which stop mistakes and the application's own account but not an owner or superuser.
- **Tamper-evident**: A property of a record or log: changes cannot be prevented in every case, but they can be detected. It makes a weaker promise than tamper-proof, which says the change cannot happen.
- **Hash chain**: A sequence of records in which each one stores a hash of the one before it, so hiding a change to an old record means recomputing every later one. It shows the log is consistent with itself, not that it is the log you originally wrote.
- **WORM storage**: Write once, read many: storage that refuses to overwrite or delete a stored object until its retention period ends. Amazon S3 Object Lock, for one, offers governance and compliance modes and legal holds.
- **Transactional outbox**: A table written in the same transaction as a change, so a message about the change is stored if and only if the change commits. A separate process then reads the table and publishes the messages.
- **Log injection**: An attack in which untrusted data, such as a username containing line breaks, is written into a log so that it forges extra entries. Structured formats such as JSON, and escaping CR and LF, prevent it.

## Common questions

### What is an audit trail?

An audit trail is a chronological record of who did what to which data, when, from where and with what result, kept so the sequence of events behind a change can be reconstructed. NIST defines it as a record that reconstructs the sequence of activities leading to a specific operation or event. It is built for accountability and investigation, so it is protected and reviewed, unlike a debugging log.

### What is the difference between an audit trail and an audit log?

NIST defines an audit log as a chronological record of system activities and an audit record as one entry in it. An audit trail is the sequence of records that reconstructs what happened around one operation or event. Many vendors, pgAudit included, use the two terms for the same thing, so read what a document means rather than which word it uses.

### What should an audit log include?

The type of event, when it happened, where, its source, the outcome and the identity of whoever or whatever was involved, which is NIST's list in control AU-3. For changes, add the target and the record before and after. Leave out passwords, tokens, keys, card numbers and anything else you could not defend seeing in the trail.

### Can an audit log be immutable?

In practice it can be tamper-evident or write-once, not impossible to alter. Insert-only permissions and triggers stop the application's account, a hash chain reveals later edits, and storage with an object lock refuses deletes until a retention period ends. Keep a copy of the latest hash somewhere the database owner cannot edit, or the chain proves little.

### How long should audit logs be kept?

As long as the rules that apply to you require, and no longer than needed. PCI DSS asks for at least 12 months, with the latest 3 months immediately available. HIPAA gives no period for logs, only six years for the documentation it requires. GDPR asks only that personal data not be kept longer than necessary, and PIPEDA asks for your own minimum and maximum periods.

### What are the best practices for audit logging?

Record the actor, action, target, UTC time, source, outcome and before and after. Write each entry in the same transaction as the change, and keep secrets out of it. Make the trail append-only, keep a copy of its latest hash elsewhere, restrict and record reads, set a retention period with a reason, and review and alert on it.

## Sources
1. [SP 800-53 Rev. 5, Security and Privacy Controls for Information Systems and Organizations](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-53r5.pdf), NIST
2. [pgAudit: Open Source PostgreSQL Audit Logging](https://github.com/pgaudit/pgaudit), pgAudit project
3. [Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html), OWASP Cheat Sheet Series
4. [Event Sourcing](https://martinfowler.com/eaaDev/EventSourcing.html), Martin Fowler
5. [Microsoft Entra ID and PCI-DSS Requirement 10](https://learn.microsoft.com/en-us/entra/standards/pci-requirement-10), Microsoft Learn
6. [PCI DSS document library](https://www.pcisecuritystandards.org/document_library/?category=pcidss&document=pci_dss), PCI Security Standards Council
7. [Just Published: PCI DSS v4.0.1](https://blog.pcisecuritystandards.org/just-published-pci-dss-v4-0-1), PCI Security Standards Council
8. [45 CFR 164.312, Technical safeguards](https://www.ecfr.gov/current/title-45/subtitle-A/subchapter-C/part-164/subpart-C/section-164.312), eCFR
9. [45 CFR 164.308, Administrative safeguards](https://www.ecfr.gov/current/title-45/subtitle-A/subchapter-C/part-164/subpart-C/section-164.308), eCFR
10. [45 CFR 164.316, Policies and procedures and documentation requirements](https://www.ecfr.gov/current/title-45/subtitle-A/subchapter-C/part-164/subpart-C/section-164.316), eCFR
11. [21 CFR Part 11, Electronic Records; Electronic Signatures](https://www.ecfr.gov/current/title-21/part-11), eCFR
12. [2017 Trust Services Criteria (With Revised Points of Focus, 2022)](https://www.aicpa-cima.com/resources/download/2017-trust-services-criteria-with-revised-points-of-focus-2022), AICPA & CIMA
13. [Regulation (EU) 2016/679 (General Data Protection Regulation)](https://publications.europa.eu/resource/cellar/3e485e15-11bd-11e6-ba9a-01aa75ed71a1.0006.03/DOC_1), Publications Office of the European Union
14. [Personal Information Protection and Electronic Documents Act](https://laws-lois.justice.gc.ca/eng/acts/p-8.6/FullText.html), Justice Laws Website, Government of Canada
15. [Personal Health Information Protection Act, 2004](https://www.ontario.ca/laws/statute/04p03), Ontario e-Laws
16. [SP 800-92, Guide to Computer Security Log Management](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-92.pdf), NIST
17. [SP 800-92 Rev. 1 (Initial Public Draft), Cybersecurity Log Management Planning Guide](https://csrc.nist.gov/pubs/sp/800/92/r1/ipd), NIST
18. [Log Management project](https://csrc.nist.gov/projects/log-management), NIST
19. [SP 800-53 Rev. 5 publication page, with the Release 5.2.0 note](https://csrc.nist.gov/pubs/sp/800/53/r5/upd1/final), NIST
20. [RFC 9162: Certificate Transparency Version 2.0](https://www.rfc-editor.org/rfc/rfc9162.html), IETF
21. [Secure Audit Logs to Support Computer Forensics](https://www.schneier.com/wp-content/uploads/2016/02/paper-auditlogs.pdf), Bruce Schneier and John Kelsey
22. [CREATE TRIGGER](https://www.postgresql.org/docs/current/sql-createtrigger.html), PostgreSQL documentation
23. [ALTER TABLE](https://www.postgresql.org/docs/current/sql-altertable.html), PostgreSQL documentation
24. [Ledger overview](https://learn.microsoft.com/en-us/sql/relational-databases/security/ledger/ledger-overview), Microsoft Learn
25. [RFC 3161: Time-Stamp Protocol (TSP)](https://www.rfc-editor.org/rfc/rfc3161.html), IETF
26. [Efficient Data Structures for Tamper-Evident Logging](https://www.usenix.org/legacy/event/sec09/tech/full_papers/crosby.pdf), Scott A. Crosby and Dan S. Wallach, USENIX Security
27. [Locking objects with Object Lock](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html), Amazon S3 User Guide
28. [Transactional outbox pattern](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html), AWS Prescriptive Guidance
29. [SET](https://www.postgresql.org/docs/current/sql-set.html), PostgreSQL documentation
30. [A09:2025 Security Logging and Alerting Failures](https://owasp.org/Top10/2025/A09_2025-Security_Logging_and_Alerting_Failures/), OWASP Top 10
