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 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 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 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 covers the logs, metrics and traces.

QuestionRecord that answers itWhat it is kept for
Why did this request fail?Application logDebugging, baselines and performance
How many requests failed this hour?MetricCounts and timings aggregated over time; they cannot say who did what
How did this order reach its current state?Event storeRebuilding state from the sequence of changes
Who changed this price, from what to what, and were they allowed to?Audit trailAccountability 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.
Fig. 1 One application produces several records, and only the trail is kept to answer who did what.

Event sourcing 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 covers event streams.

What should every audit record contain?

NIST's control AU-3, in SP 800-53 Rev. 5, 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, asks for much the same, including the affected resource. OWASP reduces both to "when, where, who and what".

For a business application that becomes seven fields:

FieldWhat to storeNotes
ActorA stable account id, the role, person or systemAn id, not a display name: names change
ActionA fixed name such as account.plan_changeA short vocabulary you can search and alert on
TargetThe type and id of what was acted onFor reads and exports, the scope and filters
TimeUTC, to the microsecondNIST's AU-8 allows UTC or a stored offset
SourceThe client address and the interface usedOWASP lists the address under "who" and the interface under "where"
Outcomesuccess, failure or denied, with a reasonPCI DSS 10.2.1.4: invalid logical access attempts
Before and afterThe affected record, wholeSecrets 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.
Fig. 2 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:

{
  "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, 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.

RuleWhat it asks forRetention it sets
PCI DSS v4.0.1, requirement 10Audit logs on all components and cardholder data, protected and reviewed dailyAt 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 informationNone for logs; six years for required documentation
21 CFR 11.10(e), FDASecure, time-stamped audit trails of changes to electronic recordsAs long as the records they cover
SOC 2An auditor's report against the AICPA Trust Services CriteriaAsk your auditor
GDPRNo audit-trail wording; security, accountability, storage limitationNo longer than necessary
PIPEDA, Schedule 1No audit-log wording; safeguards and retention guidelinesYour own minimum and maximum
Ontario PHIPA, section 10.1An electronic audit log; not yet in forceNot stated

PCI DSS v4.0.1

The PCI Security Standards Council's document library lists v4.0.1, published in June 2024, as the standard as of December 2026. Its announcement 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) 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) requires regular review of audit logs and access reports. Neither sets a retention period for logs. Section 164.316(b)(2)(i) requires six years for the documentation the rule requires.

The FDA is more specific. 21 CFR 11.10(e) 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, 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 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 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 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, 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, 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, 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 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 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 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.

LayerStopsDoes not stop
Insert-only database roleThe application's own bugs and stolen application credentialsThe table owner, superusers, anyone who changes grants
Triggers that refuse UPDATE, DELETE and TRUNCATEA role that holds the privilege using it by mistakeThe owner, who can disable them
Hash chainUnnoticed edits to past rows, once the chain is checkedAn owner who recomputes every hash, or drops the newest rows
Copy of the latest hash elsewhereThe recomputationAnyone who also controls the copy
Write-once storage, separate accountDeletion and overwriting until retention endsFalse 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, a TRUNCATE trigger can only be statement-level, so it needs its own. Mark both ENABLE ALWAYS, because per the ALTER TABLE documentation a default trigger does not fire in a session whose replication role is replica.

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.
Fig. 3 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.

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.

SELECT seq, hash_ok, link_ok FROM audit_chain_check
WHERE NOT (hash_ok AND link_ok) ORDER BY seq LIMIT 1;
 seq | hash_ok | link_ok
-----+---------+---------
   1 | f       | t

Minute Notary, 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 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 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 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.
Fig. 4 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, 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, 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 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., 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 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 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.
Fig. 5 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, whose value lasts only until the end of the transaction.

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. 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 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.
Fig. 6 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 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 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 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.