go-auditGo Audit
API Reference

Core

Auditor constructor, Config, and top-level types.

audit.New(db, config) → (Auditor, error)

Creates an Auditor backed by database/sql. The caller supplies an open *sql.DB — Go Audit never opens its own connection.

auditor, err := audit.New(sqlDB, audit.Config{
    Dialect: audit.PostgreSQL,
    UserFunc: userFromContext,
    DataAudit: audit.DataAuditConfig{Enabled: true},
})
ParamTypeDescription
db*sql.DBOpen database handle used for audit writes.
configaudit.ConfigDialect, user func, audit table configs.

Returns (Auditor, error). The returned Auditor is an interface value (see below). No DB I/O happens until you call AutoMigrate or the first CRUD through an ORM adapter.

Validation errors returned by New:

  • DataAudit.Enabled && UserFunc == nil — UserFunc required when data audit is enabled.
  • Neither DataAudit.Enabled nor APIAudit.Enabled is true.
  • DataAudit.Table or APIAudit.Table is not a valid SQL identifier.

audit.NewWithStore(store, dialect, config) → (Auditor, error)

Alternative constructor that takes any Store implementation. Useful for tests (with audit.NewMemoryStore()) or for routing audit writes through a custom persistence layer.

audit.Config

type Config struct {
    Dialect   DialectType
    UserFunc  UserFunc
    DataAudit DataAuditConfig
    APIAudit  APIAuditConfig
    Logger    func(format string, args ...any)
}
FieldPurpose
DialectOne of audit.PostgreSQL, audit.MySQL, audit.SQLite, or custom.
UserFuncResolves (userID, userType) from context on every audit write.
DataAuditData change auditing config.
APIAuditAPI call auditing config.
LoggerCalled when a storage error is swallowed under ErrorFailSilent. Optional — defaults to log.Printf.

audit.DataAuditConfig

type DataAuditConfig struct {
    Table           string
    Enabled         bool
    ExcludeFields   []string
    ExcludeEntities []string
    SkipOldValues   bool
    OnError         ErrorMode
}
FieldDefaultNotes
Table"audit_logs"Must match ^[A-Za-z_][A-Za-z0-9_]{0,62}$.
EnabledfalseMust be true (or APIAudit.Enabled must be).
ExcludeFieldsnilCase-sensitive map keys; dropped before storage.
ExcludeEntitiesnilSkip entire entity types.
SkipOldValuesfalseSkip pre-UPDATE/DELETE SELECT in adapters.
OnErrorErrorFailLoudSee ErrorMode below.

audit.APIAuditConfig

type APIAuditConfig struct {
    Table            string
    Enabled          bool
    RedactHeaders    []string
    RedactBodyFields []string
    MaxBodySize      int
    OnError          ErrorMode
}
FieldDefaultNotes
Table"audit_api_logs"Must match ^[A-Za-z_][A-Za-z0-9_]{0,62}$.
EnabledfalseEnables auditor.API().
RedactHeadersnilCase-insensitive header key match.
RedactBodyFieldsnilCase-insensitive JSON key match at any depth.
MaxBodySize4096 (bytes)Oversized bodies get truncation marker.
OnErrorErrorFailLoudSee ErrorMode below.

audit.ErrorMode

const (
    ErrorFailLoud   ErrorMode = iota // surfaces store errors to the caller (default)
    ErrorFailSilent                  // logs via Config.Logger and returns nil
)

Use ErrorFailSilent when the application write must not be coupled to audit availability (e.g. the audit DB is allowed to be briefly unavailable during maintenance).

audit.UserFunc

type UserFunc func(ctx context.Context) (userID string, userType string)

Called on every audit write. Typical implementation pulls a user out of the request context set by middleware.

func userFromContext(ctx context.Context) (string, string) {
    if u, ok := ctx.Value(userCtxKey).(*User); ok {
        return u.ID, u.Role
    }
    return "system", "system"
}

Required when DataAudit.Enabled == true.

Constants

const (
    ActionCreate     = "create"
    ActionUpdate     = "update"
    ActionDelete     = "delete"
    ActionSoftDelete = "soft_delete"
    ActionRestore    = "restore"
)

const (
    PostgreSQL DialectType = "postgres"
    MySQL      DialectType = "mysql"
    SQLite     DialectType = "sqlite"
)

Auditor Interface

type Auditor interface {
    RecordDataChange(ctx context.Context, entry DataEntry) error
    API() APIAuditor
    Query(ctx context.Context, filter DataFilter) ([]AuditLog, error)
    QueryByTransaction(ctx context.Context, txID string) (*TransactionLog, error)
    AutoMigrate(ctx context.Context) error
    Purge(ctx context.Context, before time.Time) (PurgeResult, error)
    Snapshot(ctx context.Context, entityType, entityID string, at time.Time) (map[string]any, error)
    Restore(ctx context.Context, entityType, entityID string, at time.Time) (*RestoreResult, error)
    Config() Config
}
  • RecordDataChange — manual entry point used by ORM adapters and callers writing via raw SQL. Applies diff, exclusion, and context transaction ID resolution.
  • API() — returns the APIAuditor for third-party call logging.
  • Query / QueryByTransaction — read paths (see Query & Filters).
  • AutoMigrate(ctx) — creates audit tables and indexes. Safe to call repeatedly; uses IF NOT EXISTS everywhere.
  • Purge(ctx, before) — deletes rows older than before from both tables (if enabled). Returns per-table counts.
  • Snapshot / Restore — reconstruct entity state at a past time by replaying audit history (see Query & Filters).
  • Config() — returns the configuration the Auditor was created with.

Store Helpers

audit.NewSQLStore(db *sql.DB, d Dialect) Store
audit.NewMemoryStore() Store

NewSQLStore backs the default path. NewMemoryStore is intended for tests.

On this page