EFCore.AuditLogging
1.0.8
dotnet add package EFCore.AuditLogging --version 1.0.8
NuGet\Install-Package EFCore.AuditLogging -Version 1.0.8
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="EFCore.AuditLogging" Version="1.0.8" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="EFCore.AuditLogging" Version="1.0.8" />
<PackageReference Include="EFCore.AuditLogging" />
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 EFCore.AuditLogging --version 1.0.8
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: EFCore.AuditLogging, 1.0.8"
#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 EFCore.AuditLogging@1.0.8
#: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=EFCore.AuditLogging&version=1.0.8
#tool nuget:?package=EFCore.AuditLogging&version=1.0.8
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
EFCore.AuditLogging
Entity Framework Core 审计日志记录库,用于追踪实体的增删改操作。
快速开始
步骤 1:实现审计日志实体接口
你需要创建两个实体类来实现审计日志接口:
using EFCore.AuditLogging;
// 审计日志主表
public class EfAuditLog : IEfAuditLog
{
public Guid Id { get; set; }
public string EntityId { get; set; } = string.Empty;
public string EntityName { get; set; } = string.Empty;
public string? UserId { get; set; }
public ActionType ActionType { get; set; }
public DateTime CreatOn { get; set; }
}
// 审计日志变更详情表
public class EfAuditLogChange : IEfAuditLogChange
{
public Guid Id { get; set; }
public Guid EfAuditLogId { get; set; }
public string FieldName { get; set; } = string.Empty;
public string? OldValue { get; set; }
public string? NewValue { get; set; }
}
步骤 2:实现用户标识接口
using EFCore.AuditLogging;
// 包会自动注入实现了IAuditUser的类
public class AuditUser : IAuditUser
{
public Task<string?> ObtainCurrentUserIdAsync(CancellationToken cancellationToken = default)
{
// 从当前上下文获取用户ID
// 示例:从 HttpContext、ClaimsPrincipal 等获取
return Task.FromResult("user-id");
}
}
步骤 3:注册服务
在 Program.cs 或 Startup.cs 中注册服务:
var builder = WebApplication.CreateBuilder(args);
// 注册审计日志服务
builder.Services.AddEfAuditLogger<EfAuditLog, EfAuditLogChange>(new EfAuditLoggerOptions
{
Enabled = true,
ExcludedEntities = [], // 可选:排除不需要审计的实体
RecordFullValues = false // 可选:是否记录完整的新值和旧值
});
var app = builder.Build();
步骤 4:在保存时调用审计日志
在你的 DbContext 中重写 SaveChanges 和 SaveChangesAsync 方法,调用 AuditLoggingInsert():
using Microsoft.EntityFrameworkCore;
public class YourDbContext : DbContext
{
private readonly EfAuditLoggingInserter<EfAuditLog, EfAuditLogChange> _auditLogger;
public YourDbContext(DbContextOptions<YourDbContext> options,
EfAuditLoggingInserter<EfAuditLog, EfAuditLogChange> auditLogger)
: base(options)
{
_auditLogger = auditLogger;
}
public override int SaveChanges()
{
// 调用审计日志插入方法
_auditLogger.AuditLoggingInsert();
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
// 调用审计日志插入方法
_auditLogger.AuditLoggingInsert();
return base.SaveChangesAsync(cancellationToken);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EfAuditLog>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.EntityId).IsRequired();
entity.Property(e => e.EntityName).IsRequired();
});
modelBuilder.Entity<EfAuditLogChange>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.FieldName).IsRequired();
});
base.OnModelCreating(modelBuilder);
}
}
配置选项
EfAuditLoggerOptions 提供以下配置选项:
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
Enabled |
bool | true |
是否启用日志记录 |
ExcludedEntities |
Type[] | [] |
要排除的实体类型列表 |
RecordFullValues |
bool | false |
是否记录完整的新值和旧值 |
审计日志数据结构
EfAuditLog 表(主表)
| 字段名 | 类型 | 说明 |
|---|---|---|
| Id | GUID | 审计日志ID |
| EntityId | string | 实体主键值 |
| EntityName | string | 实体名称 |
| UserId | string | 操作用户ID |
| ActionType | byte | 操作类型 (0: Added新增, 1: Modified修改, 2: Deleted删除) |
| CreatOn | datetime | 创建时间 (UTC) |
EfAuditLogChange 表(变更详情表)
| 字段名 | 类型 | 说明 |
|---|---|---|
| Id | GUID | 变更记录ID |
| EfAuditLogId | GUID | 关联的审计日志ID |
| FieldName | string | 字段名称 |
| OldValue | string | 原始值 |
| NewValue | string | 新值 |
使用示例
排除特定实体
builder.Services.AddEfAuditLogger<EfAuditLog, EfAuditLogChange>(new EfAuditLoggerOptions
{
ExcludedEntities = new[] { typeof(Log), typeof(AuditLog) }
});
查询审计日志
// 查询某个实体的审计日志
var logs = await context.Set<EfAuditLog>()
.Where(l => l.EntityName == "User" && l.EntityId == "123")
.OrderByDescending(l => l.CreatOn)
.ToListAsync();
// 查询某个审计日志的详细变更
var changes = await context.Set<EfAuditLogChange>()
.Where(c => c.EfAuditLogId == logId)
.ToListAsync();
技术细节
- 基于 EF Core 的
SaveChanges拦截机制 - 使用
ChangeTracker监听实体状态变化 - 支持异步和同步保存操作
- 自动捕获 Added(新增)、Modified(修改)、Deleted(删除)三种操作
要求
- .NET 8.0+
- Entity Framework Core 8.0.6+
安装
通过 NuGet 包管理器安装:
Install-Package EFCore.AuditLogging
或使用 .NET CLI:
dotnet add package EFCore.AuditLogging
| Product | Versions 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.
-
net8.0
- Microsoft.EntityFrameworkCore (>= 8.0.0)
- Microsoft.EntityFrameworkCore.Relational (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.DependencyModel (>= 2.1.0)
- System.Text.Json (>= 8.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
添加字段排除功能并优化变更检测逻辑