如何在基于Audit.NET的审计追踪中按月存储数据到Azure Table Storage
解决方案:Audit.NET 按月动态生成Azure存储审计表
要实现按月动态创建审计表,核心是利用Audit.NET Azure存储提供者的动态表名解析器,替代启动时固定的表名配置,让每个审计事件都能根据自身发生时间生成对应月份的表名。
步骤1:配置Audit.NET使用动态表名解析
在Startup.cs的ConfigureServices方法中,替换原固定表名的配置,改用TableNameResolver委托来动态生成表名:
using Audit.Core; using Audit.AzureStorage; using Audit.Mvc; using Audit.AspNetCore; public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { // 配置Audit.NET services.AddAudit(config => { config.Setup() .UseAzureStorageTable(provider => provider .ConnectionString(Configuration.GetConnectionString("AzureStorage")) // 动态解析表名:根据审计事件发生时间生成 .TableNameResolver(auditEvent => GenerateMonthlyTableName(auditEvent.EventDate)) // 自动创建不存在的表(默认已开启,可显式指定) .AutoCreateTable(true)); // 配置全局MVC动作过滤器 config.AddMvcAuditFilter(filterConfig => filterConfig .IncludeAllActions()); // 配置审计中间件(针对API请求) config.AddAuditMiddleware(middlewareConfig => middlewareConfig .FilterByRequest(req => req.Path.StartsWithSegments("/api"))); }); // 其他服务配置... services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 中间件管道配置... app.UseRouting(); app.UseAuthorization(); // 启用Audit中间件(需放在路由和授权之后) app.UseAuditMiddleware(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } // 生成按月命名的审计表名 private string GenerateMonthlyTableName(DateTime eventDate) { // 格式:AuditTrailJAN2024、AuditTrailFEB2024 return $"AuditTrail{eventDate.ToString("MMM").ToUpper()}{eventDate.Year}"; } }
关键说明
- TableNameResolver委托:这个委托会在每个审计事件插入前被调用,传入当前审计事件对象,通过
auditEvent.EventDate获取事件实际发生时间,以此生成对应月份的表名,彻底解决启动时固定表名的局限。 - 自动创建表:
AutoCreateTable(true)确保当目标表不存在时,Azure存储提供者会自动创建该表,无需手动提前创建。 - 表名格式合规:生成的表名符合Azure存储表的命名规则(仅含字母、数字,开头为字母,长度不超过63字符)。
验证要点
- 确保
appsettings.json中配置了正确的Azure存储连接字符串:"ConnectionStrings": { "AzureStorage": "DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net" } - 安装必要的NuGet包:
Install-Package Audit.NET Install-Package Audit.NET.AzureStorage Install-Package Audit.NET.Mvc Install-Package Audit.NET.AspNetCore
内容的提问来源于stack exchange,提问作者santosh kumar patro
相关产品推荐
相关产品推荐

