Skip to main content

Crate auditlog

Crate auditlog 

Source
Expand description

auditlog — an audit trail for your data models.

auditlog records every create / update / destroy of your models into a single polymorphic audits table, capturing what changed (a diff), who changed it, when, from where, and an optional comment — and lets you query that history and reconstruct past revisions.

auditlog is ORM-agnostic: you implement the small Auditable trait for your model and hand it a Backend. A ready-to-use async SqlxBackend (SQLite & Postgres) is included, plus an in-memory MemoryBackend for tests.

§Quick start

use auditlog::{Auditable, AuditOptions, AuditId, ValueMap, MemoryBackend};
use serde_json::json;

struct Post { id: i64, title: String, body: String }

impl Auditable for Post {
    fn auditable_type() -> &'static str { "Post" }
    fn auditable_id(&self) -> AuditId { self.id.into() }
    fn audited_attributes(&self) -> ValueMap {
        let mut m = ValueMap::new();
        m.insert("id".into(), json!(self.id));
        m.insert("title".into(), json!(self.title));
        m.insert("body".into(), json!(self.body));
        m
    }
    fn audit_options() -> AuditOptions { AuditOptions::default() }
}

let backend = MemoryBackend::new();

// create
let mut post = Post { id: 1, title: "Hello".into(), body: "...".into() };
post.audited_create(&backend).await?;

// update (diff old → new)
let old = Post { id: 1, title: "Hello".into(), body: "...".into() };
post.title = "Hello, world".into();
post.audited_update(&backend, &old).await?;

let audits = Post::audits(&backend, 1).await?;
assert_eq!(audits.len(), 2);

§Who made the change

Wrap your unit of work in an as_user scope: every audit recorded inside the scope is attributed to the given actor. The acting user is read from a tokio::task_local context, so it is isolated per task:

as_user(Actor::record("User", 7), async {
    post.audited_create(backend).await
}).await?;

§Feature flags

See the crate’s docs/SPEC.md for the exhaustive, code-accurate behavior specification.

Modules§

matchers
Configuration introspection helpers. Use these in tests to assert how a model is audited.

Structs§

Audit
One row in the audits table — an immutable record of a single change.
AuditContext
The per-task audit context.
AuditId
The identifier half of a polymorphic reference (e.g. auditable_id, user_id, associated_id).
AuditOptions
Per-model audit options controlling how a model is audited. Build with AuditOptions::builder.
AuditOptionsBuilder
Builder for AuditOptions.
AuditQuery
A composable audit query supporting filters by action (creates/updates/destroys), version range (from_version/to_version), up_until, and ascending/descending ordering.
AuditQueryBuilder
Builds and runs an audit query for a single auditable record (or its associated audits).
AuditedChanges
The serialized audited_changes payload of one audit.
GlobalConfig
Process-global configuration settings.
MemoryBackend
Stores audits in a Vec behind a Mutex. Not durable; intended for tests.
NewAudit
An audit about to be written. The version is assigned by the backend at insert time (forced to 1 for create, otherwise max(version) + 1 for the auditable).
ParseActionError
Returned when a string cannot be parsed into an Action.
Revision
A reconstructed snapshot of an auditable record at a point in its history.

Enums§

Action
One audited lifecycle action.
Actor
Who performed an audited change.
AuditError
Errors that can occur while recording or querying audits.
ChangeValue
A single interpreted change entry.
Order
Result ordering for an audit query.
SqlxBackend
The sqlx-backed Backend. Construct with SqlxBackend::sqlite or SqlxBackend::postgres, then call SqlxBackend::migrate once to create the audits table.
UndoPlan
The reverse operation for an audit, produced by Audit::undo_plan.

Constants§

DEFAULT_IGNORED_ATTRIBUTES
Default columns never recorded in any diff.
FILTERED
The placeholder used for encrypted attributes (distinct from REDACTED).
REDACTED
The default placeholder used for redacted columns (audited redacted: ...).

Traits§

Auditable
Make a model auditable.
Backend
Where to store and how to retrieve audits.

Functions§

as_user
Attribute all audits written while f runs to user. Inherits the rest of the current context and restores it afterward; nests correctly.
as_user_sync
Synchronous as_user.
auditing_enabled
Whether the process-global master switch is on.
config
Mutate the global configuration.
current_context
Clone the current task-local context, or a default if no scope is active.
global_config
Snapshot the current global configuration.
global_max_audits
The global retention cap (if any).
set_auditing_enabled
Set the process-global master auditing switch.
set_type_enabled
Persistently enable/disable auditing for one auditable type. Within a crate::without_auditing / crate::with_auditing scope, the scope wins for the duration of the block.
type_enabled
Whether a type’s persistent flag is on (defaults to true).
with_auditing
Force auditing on while f runs, even if the type was disabled. Has no effect if the global master switch is off.
with_auditing_sync
Synchronous with_auditing.
with_context
Run f with ctx as the active context.
with_context_sync
Run f synchronously with ctx as the active context.
without_auditing
Suppress all audits written while f runs.
without_auditing_sync
Synchronous without_auditing.

Type Aliases§

Result
Convenience alias used throughout the crate.
ValueMap
An ordered map of column name to JSON value.

Attribute Macros§

async_trait
Re-export so downstream code and doc examples can reference the same async_trait.