Examples
Basic Example
GORM + PostgreSQL, data audit only.
This example demonstrates the simplest possible Go Audit setup: GORM connected to PostgreSQL with data change auditing enabled.
Complete Code
package main
import (
"context"
"fmt"
"log"
"github.com/gopackx/go-audit"
auditgorm "github.com/gopackx/go-audit/adapters/gorm"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Product struct {
ID uint `gorm:"primaryKey"`
Name string
Price int
}
type ctxKey string
const userIDKey ctxKey = "user_id"
func main() {
dsn := "host=localhost user=postgres password=postgres dbname=shop port=5432 sslmode=disable"
gormDB, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
sqlDB, err := gormDB.DB()
if err != nil {
log.Fatal(err)
}
auditor, err := audit.New(sqlDB, audit.Config{
Dialect: audit.PostgreSQL,
UserFunc: func(ctx context.Context) (string, string) {
if u, ok := ctx.Value(userIDKey).(string); ok {
return u, "user"
}
return "system", "system"
},
DataAudit: audit.DataAuditConfig{Enabled: true},
})
if err != nil {
log.Fatal(err)
}
if err := gormDB.Use(auditgorm.Plugin(auditor)); err != nil {
log.Fatal(err)
}
ctx := context.Background()
if err := auditor.AutoMigrate(ctx); err != nil {
log.Fatal(err)
}
if err := gormDB.AutoMigrate(&Product{}); err != nil {
log.Fatal(err)
}
ctx = context.WithValue(ctx, userIDKey, "user-42")
tx := gormDB.WithContext(ctx)
p := Product{Name: "Keyboard", Price: 150}
tx.Create(&p)
tx.Model(&p).Update("Price", 129)
tx.Delete(&p)
logs, _ := auditor.Query(ctx, audit.DataFilter{EntityType: "products"})
for _, l := range logs {
fmt.Printf("[%s] %s#%s by %s\n", l.Action, l.EntityType, l.EntityID, l.UserID)
}
}Output
[create] products#1 by user-42
[update] products#1 by user-42
[delete] products#1 by user-42Inspect the audit_logs table directly and you'll see each row's
old_values and new_values populated correctly — the update row
only contains the price field because that's the only one that
changed.
Next
- Add API call logging
- Use multiple databases
- See the full example