Auditing
ant has four places to record a change.
| You need | Use |
|---|---|
| Field-level history of saves | SaveInterceptor |
| A record that can't disagree with the data | A row in the same Tx |
| A reaction after the commit | Observer |
| Delivery that survives a crash | An outbox row and a worker |
| Bulk writes and raw SQL too | Interceptor, or a database trigger |
Log what changed, field by field
A SaveInterceptor sees every save before it writes, as whole entities with the names of the fields that changed. It runs for SaveChanges and for single-entity writes such as Insert. An error cancels the save.
type AuditTrail struct {
log *slog.Logger
}
func (a *AuditTrail) Before(ctx context.Context, _ *ant.Statement) (context.Context, error) {
return ctx, nil
}
func (a *AuditTrail) After(context.Context, *ant.Statement, ant.Outcome) {}
func (a *AuditTrail) SavingChanges(ctx context.Context, changes []ant.Change) error {
for _, c := range changes {
a.log.Info("saving", "model", c.Model, "state", c.State.String(), "fields", c.Changed)
}
return nil
}
db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn, ant.WithInterceptor(&AuditTrail{logger}))
Changing a user's age from 30 to 31 and calling SaveChanges logs model=User state=Modified fields=[Age] and then writes:
UPDATE "users" SET "age" = $1, "updated_at" = $2 WHERE "users"."id" = $3
Record the old values
The interceptor sees which fields changed, not their old values. ant.Original reads the value as loaded:
func logAge(ctx context.Context, db *AppDB, user *User) error {
entry, err := ant.Entry(ctx, db, user)
if err != nil {
return err
}
was, err := ant.Original(entry, &Users.Age)
if err != nil {
return err
}
logger.Info("age changed", "from", was, "to", user.Age)
return nil
}
Pass Entry the context you were given: inside a hook or interceptor it shares that operation's claim on the tracker, and a context from elsewhere gets ErrConcurrentUse while another operation holds it. Original returns ErrNotTracked for an entity with no loaded values.
Write an audit row in the same transaction
To keep the record consistent with the data, write it in the same transaction as the change.
err := db.Tx(ctx, func(tx *AppDB) error {
if err := tx.Orders.Insert(ctx, order); err != nil {
return err
}
return tx.AuditLog.Insert(ctx, &AuditEntry{Action: "order.created", Subject: order.ID})
})
// INSERT INTO "orders" DEFAULT VALUES RETURNING "id"
// INSERT INTO "audit_entries" ("action", "subject") VALUES ($1, $2) RETURNING "id"
// -- $1 = 'order.created', $2 = the new order's id
A hook only gets a context.Context and cannot reach the transaction, so use hooks to check or refuse, not to write rows.
React after the commit
An observer runs after the commit, never for a rollback or failed commit. It runs in your process, so a crash loses it.
For anything that must not be lost, write an outbox row in the transaction, as the ledger example does, and let a worker send it.
Record every statement
An Interceptor sees every statement, including bulk writes and raw SQL, as SQL rather than entities.
Bulk Update and Delete, InsertMany and Raw don't run hooks or a SaveInterceptor, since they load no entity. Only a database trigger sees everything, including someone typing into psql.
For a whole audit service, see the audit example.