Key points
- An audit log answers “who did what, when, to which record”; it is not your debug log.
- Write each event in the same transaction as the change, with an explicit list of tracked fields.
- Make it append-only at the database level, with retention set per plan.
Once a SaaS product is used by teams rather than individuals, support starts getting the same kind of ticket: who changed this user’s role, who deleted that client, why did the price change. Without an audit log, answering means digging through server logs, if they have not been rotated away already. We now add one in the first releases of every SaaS we build: it costs little at the start and is painful to reconstruct later.
What goes in, and what stays out
An audit event needs only a handful of fields: tenant, actor, action, subject, changes and time. A few choices save a lot of grief down the line.
- Copy the actor’s display name when writing the event, so the row still makes sense after that user is deleted.
- Record the actor type: a user, an API key, a scheduled job, or your own support staff. Customers should be able to see when you stepped in.
- Never store passwords, tokens or card data, hashed or not. Far more people read an audit log than query the database.
CREATE TABLE audit_events (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
tenant_id BIGINT UNSIGNED NOT NULL,
actor_type VARCHAR(20) NOT NULL, -- user, api_key, system, support
actor_id BIGINT UNSIGNED NULL,
actor_label VARCHAR(190) NOT NULL, -- copied at write time
action VARCHAR(80) NOT NULL, -- member.role_changed, invoice.deleted
subject_type VARCHAR(40) NOT NULL,
subject_id VARCHAR(64) NOT NULL,
changes JSON NULL,
ip VARBINARY(16) NULL,
created_at DATETIME(3) NOT NULL,
KEY tenant_time (tenant_id, created_at),
KEY tenant_subject (tenant_id, subject_type, subject_id)
);
Action names follow an object.verb_past convention. That consistency is what lets you offer meaningful filters in the UI later.
Writing the event at the right moment
The most common bug we find in inherited code: the audit row is written after commit, or pushed onto a queue. The first time something fails halfway, you get a change with no trace, or a trace with no change. We write the event inside the same transaction.
function audit(PDO $db, Actor $actor, string $action, string $type, string $id,
array $before = [], array $after = [], array $tracked = []): void
{
$changes = [];
foreach ($tracked as $field) { // allowlist, never the whole row
$old = $before[$field] ?? null;
$new = $after[$field] ?? null;
if ($old !== $new) {
$changes[$field] = ['from' => $old, 'to' => $new];
}
}
$db->prepare('INSERT INTO audit_events
(tenant_id, actor_type, actor_id, actor_label, action, subject_type, subject_id, changes, ip, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, UTC_TIMESTAMP(3))')
->execute([
$actor->tenantId, $actor->type, $actor->id, $actor->label,
$action, $type, $id,
$changes ? json_encode($changes) : null,
$actor->ip ? inet_pton($actor->ip) : null,
]);
}
// Usage: same transaction as the change itself
$db->beginTransaction();
$before = $members->find($memberId);
$members->changeRole($memberId, 'admin');
audit($db, $actor, 'member.role_changed', 'member', (string) $memberId,
$before, ['role' => 'admin'] + $before, ['role']);
$db->commit();
The tracked fields are listed explicitly. Dumping the whole row before and after looks simpler until someone adds a sensitive column to that table and it starts appearing in the log without anyone deciding it should.
Making it tamper-resistant
A log the application can edit proves very little. The cheapest fix is to let the database enforce it:
-- The application can write and read, never rewrite history
GRANT SELECT, INSERT ON app.audit_events TO 'app'@'%';
-- Only the retention job may delete, with its own account
GRANT SELECT, DELETE ON app.audit_events TO 'retention'@'localhost';
Retention, for example longer history on higher plans, then runs as a separate job under its own account.
Showing it to customers
A paginated list filterable by member, record type and date range covers most needs, plus a CSV export for customers who have their own compliance reviews. The (tenant_id, created_at) index keeps those screens fast as the table grows, and every query is scoped to the tenant, like everything else in the app.
FAQ
Why not use database triggers instead?
Triggers capture data changes well, but they cannot tell who acted or why, since the database only sees the application’s account. We keep them for narrow cases and log at the application level.
Should we log reads too?
Not by default; the volume gets out of hand. We only log sensitive access: data exports, opening a restricted record, or a support engineer signing in to a customer account.
Building or growing a SaaS product? We help with architecture, multi-tenant security and the features business customers expect before they sign.



