NB.EfCore.AuditLog 1.1.0

dotnet add package NB.EfCore.AuditLog --version 1.1.0
                    
NuGet\Install-Package NB.EfCore.AuditLog -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NB.EfCore.AuditLog" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NB.EfCore.AuditLog" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="NB.EfCore.AuditLog" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NB.EfCore.AuditLog --version 1.1.0
                    
#r "nuget: NB.EfCore.AuditLog, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NB.EfCore.AuditLog@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NB.EfCore.AuditLog&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=NB.EfCore.AuditLog&version=1.1.0
                    
Install as a Cake Tool

EfCore.AuditLog

NuGet License: MIT

Audit logging for Entity Framework Core using SaveChangesInterceptor.

It tracks INSERT, UPDATE, and DELETE operations, stores old and new value snapshots as JSON, and can attach user, tenant, source, and trace metadata through a pluggable provider.

Features

  • Zero changes to your existing SaveChanges() and SaveChangesAsync() calls
  • Opt-in or opt-out auditing with [Auditable] and ignore rules
  • Per-operation ignore rules (IgnoreOperations), e.g. skip only inserts of an entity type
  • Day-by-day archiving of old audit rows to gzip JSONL with SHA256 verification (AuditArchiver)
  • Property-level filtering with [AuditIgnore] or global ignored property names
  • User-context enrichment through IAuditUserProvider
  • Same-transaction persistence so audit rows are committed atomically with the business change
  • Support for insert, update, and delete snapshots
  • Tested against SQLite with coverage for core interceptor behavior

Installation

Install-Package EfCore.AuditLog

Or with the .NET CLI:

dotnet add package EfCore.AuditLog

Requirements

  • .NET 8.0
  • EF Core 7.0 or later

Quick Start

1. Configure audit options and services

var auditOptions = new AuditOptions
{
    Mode = AuditMode.OptIn,
    TableName = "audit_logs"
    // Schema = "audit"
};

auditOptions.IgnoreProperties("PasswordHash", "SecurityStamp");

builder.Services.AddAuditLogging(options =>
{
    options.Mode = auditOptions.Mode;
    options.TableName = auditOptions.TableName;
    options.Schema = auditOptions.Schema;
    options.EnableMultiTenancy = auditOptions.EnableMultiTenancy;
    options.IgnoreProperties("PasswordHash", "SecurityStamp");
});

builder.Services.AddScoped<IAuditUserProvider, MyAuditUserProvider>();

builder.Services.AddDbContext<AppDbContext>((sp, options) =>
{
    options.UseSqlServer(connectionString);
    options.AddAuditInterceptor(sp);
});

2. Configure your DbContext

public class AppDbContext : DbContext
{
    private readonly AuditOptions _auditOptions;

    public AppDbContext(DbContextOptions<AppDbContext> options, AuditOptions auditOptions)
        : base(options)
    {
        _auditOptions = auditOptions;
    }

    public DbSet<AuditLogEntry> AuditLogs => Set<AuditLogEntry>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyAuditLogConfiguration(_auditOptions);
    }
}

3. Mark entities for auditing

[Auditable]
public class Order
{
    public int Id { get; set; }
    public string CustomerName { get; set; } = null!;
    public decimal Total { get; set; }

    [AuditIgnore]
    public string? InternalNotes { get; set; }
}

4. Implement IAuditUserProvider

using System.Security.Claims;
using EfCore.AuditLog.Abstractions;

public sealed class MyAuditUserProvider : IAuditUserProvider
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MyAuditUserProvider(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public string? GetUserId()
        => _httpContextAccessor.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;

    public string? GetUserEmail()
        => _httpContextAccessor.HttpContext?.User?.FindFirst(ClaimTypes.Email)?.Value;

    public string? GetTenantId()
        => _httpContextAccessor.HttpContext?.Request.Headers["X-Tenant-Id"].FirstOrDefault();

    public string? GetSource() => "MyApp";

    public string? GetTraceId() => _httpContextAccessor.HttpContext?.TraceIdentifier;
}

What Gets Logged

Operation OldValues NewValues
INSERT null All non-ignored properties
UPDATE Modified properties only, using original values Modified properties only, using current values
DELETE All non-ignored properties null

Each audit row stores:

  • Table name
  • Record identifier
  • Operation type
  • JSON snapshots of old and new values
  • User, email, tenant, source, and trace information when available
  • UTC timestamp of the change

Configuration Options

services.AddAuditLogging(options =>
{
    options.TableName = "audit_logs";
    options.Schema = null;
    options.Mode = AuditMode.OptIn;
    options.EnableMultiTenancy = false;

    options.IgnoreEntities(typeof(TempLog));
    options.IgnoreOperations(typeof(OrderLine), AuditOperation.Insert);
    options.IgnoreProperties("PasswordHash", "SecretKey");
});

Skipping Single Operations

IgnoreEntities drops an entity type completely. IgnoreOperations drops only some operations of a type, for example rows that are created in bulk from a template while their later updates still matter:

services.AddAuditLogging(options =>
{
    // Only updates and deletes of OrderLine are audited.
    options.IgnoreOperations(typeof(OrderLine), AuditOperation.Insert);

    // Never audited; the same as options.IgnoreEntities(typeof(CacheEntry)).
    options.IgnoreOperations<CacheEntry>(AuditOperation.All);

    // Inserts of empty rows are skipped, inserts that already carry a value are audited.
    options.IgnoreOperations<OrderLine>(AuditOperation.Insert, when: line => line.Quantity == 0);
});
  • AuditOperation is a flags enum (Insert, Update, Delete, All); repeated calls for one type add up.
  • The entity type is matched exactly, as with IgnoreEntities: a rule for a base class does not cover its subclasses.
  • AuditOptions.IgnoredOperations lists the unconditional rules, ConditionallyIgnoredOperations the conditional ones (useful for a startup log line). A conditional predicate that throws audits the change.

Archiving Old Audit Rows

AuditArchiver moves audit rows older than a retention period out of the database, one UTC day at a time. It does not know about any storage; you implement IAuditArchiveStore (S3, MinIO, a file share...).

public sealed class S3AuditArchiveStore : IAuditArchiveStore
{
    // GetManifestAsync: object metadata -> AuditArchiveManifest.FromMetadata(...), or null if the key does not exist
    // UploadAsync:      put the stream with manifest.ToMetadata() as object metadata; never overwrite an existing key
    // OpenReadAsync:    the object's content stream
}

var archiver = new AuditArchiver(); // BatchSize = 5000
var result = await archiver.ArchiveNextDayAsync(
    dbContext,
    store,
    day => $"{tenantId}/my-service/{day:yyyy}/{day:MM}/{day:yyyy-MM-dd}.jsonl.gz",
    cutoffUtc: DateTime.UtcNow.AddDays(-30));

// result: Day, Rows, ObjectKey, Deleted, Resumed, Done (true = nothing older than the cutoff is left)

One call archives one day:

  1. FindOldestDayAsync: the oldest day with rows that lies entirely before the cutoff (the cutoff is truncated to UTC midnight, so no row younger than the cutoff is ever archived). None → Done.
  2. ExportDayAsync: the day's rows ordered by id, read in batches, written as gzip JSONL to a temporary file. Returns an AuditArchiveManifest: day, row count, first and last id, SHA256 of the uncompressed content, format version.
  3. Upload under the day's key with the manifest as metadata. An existing object is never replaced: if the key already exists (an earlier run stopped after the upload), that object and its manifest are used instead.
  4. VerifyAsync: read the object back, count lines and compare the SHA256 with the manifest.
  5. Every row of that day still in the database must be in the object, otherwise nothing is deleted.
  6. DeleteRangeAsync: delete rows with id between the manifest's first and last id and on that day, in batches; each batch is a single DELETE statement (its own transaction when no ambient transaction exists).

Any disagreement between the object, its manifest and the database throws AuditArchiveException before anything is deleted; it needs a human. Call it repeatedly (e.g. from a nightly job) until Done.

The JSONL format (version 1) has one object per line with the keys id, table_name, record_id, operation, old_values, new_values, user_id, user_email, tenant_id, source, trace_id, changed_at_utc. old_values and new_values are nested JSON, not strings, so zcat day.jsonl.gz | jq 'select(.table_name == "orders")' works directly. A value that is not valid JSON is kept as a string.

The archiver queries DbContext.Set<AuditLogEntry>(), so the audit table must be mapped with ApplyAuditLogConfiguration; an index on ChangedAtUtc keeps FindOldestDayAsync cheap.

Notes

  • The package persists audit rows in the same save pipeline as the business operation.
  • This favors consistency and atomicity over fully decoupled background logging.
  • For inserted entities with database-generated keys, the interceptor performs a follow-up save to populate the final RecordId.
  • If you customize TableName or Schema, pass the same AuditOptions instance into ApplyAuditLogConfiguration(...) in your DbContext.

Release Notes

See CHANGELOG.md for version history.

License

MIT

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 66 11/14/2026
1.0.0 4,373 4/19/2026

1.1.0: AuditOperation flags and AuditOptions.IgnoreOperations (skip only inserts, updates or deletes of an entity type; IgnoreEntities = all operations). AuditArchiver: find the oldest day before a cutoff, export a day as gzip JSONL with a SHA256 manifest, verify an archive, delete exactly the archived id range of that day in batches, and ArchiveNextDayAsync that ties it together over a pluggable IAuditArchiveStore.