The Audit Log You Keep Reinventing
Every app needs an audit trail eventually. I've built the same thing six different ways over the years - here's when a plain DB table is enough and when it isn't.
Every project eventually needs an audit trail. Someone at the client asks "who changed that order status?" or compliance requires you to retain a record of every data mutation, or - and this is the fun one - a user swears they never made a change and you have no way to prove otherwise. I've been there more times than I can count, and I've built the audit log from scratch probably six or seven times in my career.
The honest truth is that a plain database table handles maybe 80% of real-world audit requirements just fine. The other 20% will make you regret not thinking harder upfront.
What an audit log actually needs to do
Strip away the marketing and the architecture diagrams and an audit log has three jobs:
- Record what changed, what it changed from, and what it changed to.
- Record who did it and when.
- Make that record tamper-evident - preferably tamper-proof.
Most homegrown solutions nail 1 and 2 and completely ignore 3. That third requirement is where the "build" path starts to get complicated.
The simple version - and it really is fine for most apps
For a healthcare client a few years back I built what I'll call the "audit_log table" approach. It looked like this:
CREATE TABLE audit_logs (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
auditable_type VARCHAR(255) NOT NULL,
auditable_id BIGINT NOT NULL,
event VARCHAR(50) NOT NULL, -- created, updated, deleted
old_values JSONB,
new_values JSONB,
ip_address INET,
user_agent TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_audit_logs_auditable ON audit_logs (auditable_type, auditable_id);
CREATE INDEX idx_audit_logs_user_id ON audit_logs (user_id);
CREATE INDEX idx_audit_logs_created_at ON audit_logs (created_at);
In Laravel I wire this up with an Auditable trait on whatever models need tracking:
trait Auditable
{
public static function bootAuditable(): void
{
static::created(function ($model) {
static::writeAudit($model, 'created', [], $model->getAttributes());
});
static::updated(function ($model) {
static::writeAudit($model, 'updated', $model->getOriginal(), $model->getChanges());
});
static::deleted(function ($model) {
static::writeAudit($model, 'deleted', $model->getAttributes(), []);
});
}
protected static function writeAudit($model, string $event, array $old, array $new): void
{
// Strip columns you never want logged
$exclude = $model->auditExclude ?? ['password', 'remember_token', 'updated_at'];
AuditLog::create([
'user_id' => auth()->id(),
'auditable_type' => get_class($model),
'auditable_id' => $model->getKey(),
'event' => $event,
'old_values' => array_diff_key($old, array_flip($exclude)) ?: null,
'new_values' => array_diff_key($new, array_flip($exclude)) ?: null,
'ip_address' => request()->ip(),
'user_agent' => request()->userAgent(),
]);
}
}
Then on any model:
class PatientRecord extends Model
{
use Auditable;
protected array $auditExclude = ['password', 'remember_token', 'updated_at', 'last_synced_at'];
}
This is genuinely useful. It costs maybe half a day to build, it integrates cleanly with Eloquent lifecycle hooks, and querying it is dead simple:
// Everything that happened to a specific record
$history = AuditLog::where('auditable_type', PatientRecord::class)
->where('auditable_id', $recordId)
->with('user')
->orderBy('created_at', 'desc')
->get();
// Everything a user did in the last 30 days
$userActivity = AuditLog::where('user_id', $userId)
->where('created_at', '>=', now()->subDays(30))
->get();
For internal tools, admin panels, e-commerce back-offices, most SaaS dashboards - this is enough. Ship it and move on.
There's also owen-it/laravel-auditing if you want a polished package that does essentially this but with more configuration surface. I've used it. It's good. If you don't have an opinion about the schema, just grab the package and get on with your life.
Where the simple version breaks down
Here's where I've gotten burned.
Volume. A print management client I work with processes thousands of job status transitions per day. After 18 months, the audit_logs table had 40 million rows. Queries that were instant on day one started taking seconds. Postgres JSONB is great but it's not magic - you can't index inside the diff blobs without getting creative, and reporting queries that join across auditable types become painful fast. Partitioning helps, but now you're maintaining partitioning logic, which is its own project.
Tamper-evidence. A database row can be edited. If your audit log lives in the same database as your application data, an attacker with write access to your DB - or a rogue developer - can silently alter or delete records. For most internal tools nobody cares. For anything touching HIPAA, SOC 2, PCI, or financial services, somebody cares. A lot.
Background jobs and queue workers. The auth()->id() call returns null in a queued job. I've seen audit logs full of null user_ids because someone forgot to pass actor context into the job. You can work around this by injecting a "performed_by" parameter explicitly, but it's friction you have to design around.
Cross-service attribution. Once you're more than one service, the audit log-per-database approach means you have no unified trail. I haven't hit this personally at NWOS scale - we build monoliths - but I've seen it become a mess quickly when clients add microservices.
Soft deletes. If you use SoftDeletes on a model, Eloquent's deleted event fires when the row is soft-deleted. If you later force-delete, you fire again. If you restore, the restored event doesn't fire the trait's listener at all unless you explicitly hook it. These are edge cases but they produce gaps that clients notice.
When to reach for something purpose-built
After you've hit volume problems or compliance requirements, the conversation shifts. The two categories I've actually evaluated:
Dedicated audit log services. Things like Treblle, Datadog Audit Logs, or the purpose-built Sequin approach (database CDC to a separate store) take the write path out of your application entirely and give you a separate queryable store with retention policies baked in. The pitch is: your app fires an event, they handle the rest, the records are outside your blast radius.
I evaluated this for a biotech client who needed a 7-year immutable audit trail for FDA compliance. The "send an event to an external service" model is appealing until you think hard about what happens when that service is down during a critical write. Do you block the write? Do you queue the audit event and risk a gap? The answers are solvable but they're not free.
Database CDC (Change Data Capture). Postgres logical replication to something like a separate audit store via Debezium or pgaudit is legitimately tamper-resistant because it operates below the application layer. A rogue query that updates a row can't suppress the WAL entry. This is the right answer for serious compliance requirements. It's also meaningfully more infrastructure to operate, and your DevOps costs go up.
For the biotech client we ended up with pgaudit logging to a separate read-only Postgres instance with restricted access. Not glamorous, but auditors were satisfied and I didn't have to integrate a new SaaS dependency.
My actual decision tree
When a new project comes up and audit logging is on the requirements list:
- Is this an internal admin tool or a small SaaS? Eloquent trait plus a table. Done in an afternoon. Use the laravel-auditing package if you want to skip the boilerplate.
- Is there a compliance requirement (HIPAA, SOC 2, PCI, FDA)? You need tamper-evidence. That means CDC or pgaudit to a separate store at minimum. Budget for it.
- Will this table see more than a few million rows in year one? Add Postgres partitioning by month from day one. Retrofitting it later is a painful afternoon you don't need.
- Are background jobs the primary writers? Build an explicit audit context - a singleton or a request-scoped object you inject with the actor before dispatching - rather than relying on
auth()->id(). - Do you need cross-entity reporting? ("Show me everything that changed between 2PM and 3PM yesterday across all entity types.") A flat table with a composite index on
created_atworks fine here as long as you're not at scale.
The buy options worth knowing about
If you're evaluating third-party solutions, the ones I've looked at seriously:
- laravel-auditing - The obvious first stop for Laravel shops. Mature, well-documented, flexible drivers. Free.
- Papertrail (the gem, not the log service) - Rails world, but worth understanding their model for the design ideas.
- Neon + logical replication - If you're on Neon Postgres, their branching and WAL access makes CDC setups significantly less painful than self-hosted.
- Datadog Audit Trail - Fine if you're already deep in Datadog. Overkill if you're not.
I haven't found a SaaS audit log product that made me say "yes, obviously." Most of them charge per event and add a network hop per write. For high-volume systems those costs compound fast.
Closing
The audit log you build in an afternoon is probably fine for longer than you think. The mistake I see is waiting until a compliance audit or a production incident to think about it at all - at that point you're retrofitting under pressure and the gaps in your history are already there. Build the simple version early, understand its limits, and have a clear trigger for when you'd upgrade. For most of the work I do, the trigger is "an auditor or a lawyer gets involved" - and until then, a Postgres table and an Eloquent trait is as much infrastructure as the problem deserves.
Need help shipping something like this? Get in touch.