Search code examples
c#asp.net-core-3.1audit.net

How to ingest data to AzureTableStorage month wise in the AuditTrail implementation using Audit.NET?


I have implemented Audit Trail in asp.net core 3.1 application using great library which has a very good documentation also : https://github.com/thepirat000/Audit.NET/blob/master/src/Audit.WebApi/README.md

I have implemented it in a asp.net core 3.1 web api project with the recommended approach : Middleware + Action Filters (Asp.Net Core): Adding the Audit Middleware together with the Global Action Filter (or Local Action Filters). In this implementation I am using AzureStorageTableDataProvider (https://github.com/thepirat000/Audit.NET/tree/master/src/Audit.NET.AzureStorageTables) to store the audit events.

Audit.Core.Configuration.Setup()
    .UseAzureTableStorage(config => config
        .Endpoint(new Uri(Settings.TableEndpointUrl))
        .TableName(Settings.TableName)
        .ClientOptions(new TableClientOptions() { Retry = { MaxRetries = 66 } })
        .EntityBuilder(builder => builder
            .PartitionKey(auditEvent => auditEvent.EventType)
            .RowKey(auditEvent => Guid.NewGuid().ToString("N"))
            .Columns(col => col
                .FromDictionary(auditEvent => new Dictionary<string, object>()
                {
                    { "EventType", auditEvent.EventType },
                    { "UserName", auditEvent.Environment.UserName },
                    { "EventDuration", auditEvent.Duration },
                    { "Data", auditEvent.ToJson() }
                }))));

The above code gets invoked from the Configure method of Startup.cs. This code gets invoked only at the startup event of the application and from there on all the requests are intercepted by the middleware and gets stored. In the above code only one table gets created if it does not exists at the startup time and from there on the same table is used for storing the data. In my case I want to have a table getting created by month ( for example AuditTrailJAN2024, AuditTrailFEB2024). I created a method : GetTableName() which returns the table name dynamically and updated the above code .TableName(GetTableName()) but this does not work for me since the above logic gets invoked for the first time and subsequently whenever the app restarts.

Can anyone help me here with some code sample which will serve as a reference for my implementation


Solution

  • Looks like you're calling the wrong overload of TableName(). If you need your table name to be dynamic, you must use TableName(Func<AuditEvent, string>) overload.

    For example:

         .TableName(ev => GetTableName())