ecto_trail v0.3.0 EctoTrail

EctoTrail allows to store changeset changes into a separate audit_log table.

Usage

  1. Add ecto_trail to your list of dependencies in mix.exs:

    def deps do [{:ecto_trail, "~> 0.1.0"}] end

  2. Ensure ecto_trail is started before your application:

    def application do [extra_applications: [:ecto_trail]] end

  3. Add a migration that creates audit_log table to priv/repo/migrations folder:

    defmodule EctoTrail.TestRepo.Migrations.CreateAuditLogTable do @moduledoc false use Ecto.Migration

    def change do

    create table(:audit_log, primary_key: false) do
      add :id, :uuid, primary_key: true
      add :actor_id, :string, null: false
      add :resource, :string, null: false
      add :resource_id, :string, null: false
      add :changeset, :map, null: false
    
      timestamps([type: :utc_datetime, updated_at: false])
    end

    end end

  4. Use EctoTrail in your repo:

    defmodule MyApp.Repo do use Ecto.Repo, otp_app: :my_app use EctoTrail end

  5. Use logging functions instead of defaults. See EctoTrail module docs.

You can configure audit_log table name (default audit_log) in config:

config :ecto_trail,

table_name: "custom_audit_log_name"

If you use multiple Repo and audit_log should be stored in tables with different names, you can configure Schema module for each Repo:

defmodule MyApp.Repo do
  use Ecto.Repo, otp_app: :my_app
  use EctoTrail, schema: My.Custom.ChangeLogSchema
end

Link to this section Summary

Functions

Call Ecto.Repo.insert/2 operation and store changes in a change_log table

Call Ecto.Repo.update/2 operation and store changes in a change_log table

Link to this section Functions

Link to this function

insert_and_log(repo, struct_or_changeset, actor_id, opts \\ [])
insert_and_log(
  repo :: Ecto.Repo.t(),
  struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(),
  actor_id :: String.T,
  opts :: Keyword.t()
) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}

Call Ecto.Repo.insert/2 operation and store changes in a change_log table.

Insert arguments, return and options same as Ecto.Repo.insert/2 has.

Link to this function

update_and_log(repo, changeset, actor_id, opts \\ [])
update_and_log(
  repo :: Ecto.Repo.t(),
  changeset :: Ecto.Changeset.t(),
  actor_id :: String.T,
  opts :: Keyword.t()
) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}

Call Ecto.Repo.update/2 operation and store changes in a change_log table.

Insert arguments, return and options same as Ecto.Repo.update/2 has.