RapidGo
No results found

Audit Logging

Track user actions and model changes with a database-backed audit trail.

The audit package records user actions and model changes to a database table for compliance and debugging.

Setup

import "github.com/RAiWorks/RapidGo/v2/core/audit"

// Create an audit logger (auto-migrates the audit_logs table)
logger := audit.NewLogger(db)

Logging Actions

logger.Log(audit.Entry{
    UserID:    currentUser.ID,
    Action:    "update",
    ModelType: "Post",
    ModelID:   post.ID,
    OldValues: map[string]interface{}{"title": "Old Title"},
    NewValues: map[string]interface{}{"title": "New Title"},
    Metadata:  map[string]interface{}{"ip": clientIP},
})

Querying Audit Logs

// Find by custom query
logs, err := logger.Find("user_id = ?", 42)

// Find all changes for a specific model
logs, err := logger.ForModel("Post", postID)

Audit Log Schema

Field Type Description
ID uint Auto-incrementing primary key
UserID uint User who performed the action
Action string Action type (create, update, delete, etc.)
ModelType string Model name (e.g., "Post", "User")
ModelID uint ID of the affected model
OldValues JSON text Previous values (for updates)
NewValues JSON text New values (for creates/updates)
Metadata JSON text Additional context (IP, user agent, etc.)
CreatedAt timestamp When the action occurred

Entry Struct

type Entry struct {
    UserID    uint
    Action    string
    ModelType string
    ModelID   uint
    OldValues map[string]interface{}
    NewValues map[string]interface{}
    Metadata  map[string]interface{}
}