Store Audit.NET Trail Logs into an Azure Cosmos database
$ dotnet add package Audit.NET.AzureCosmosAzure Cosmos DB (Document DB SQL API) provider for Audit.NET library. (An extensible framework to audit executing operations in .NET)
Store the audit events in an Azure Cosmos DB collection, in JSON format.
NuGet Package To install the package run the following command on the Package Manager Console:
PM> Install-Package Audit.NET.AzureCosmos
Please see the Audit.NET Readme
Set the static Audit.Core.Configuration.DataProvider property to set the Cosmos DB data provider,
or use the UseAzureCosmos method on the fluent configuration. This should be done before any AuditScope creation, i.e. during application startup.
For example:
Audit.Core.Configuration.DataProvider = new Audit.AzureCosmos.Providers.AzureCosmosDataProvider(config => config
.Endpoint("https://mycompany.documents.azure.com:443/")
.AuthKey("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==")
.Database("Audit")
.Container("logs")
.WithId(_ => Guid.NewGuid().ToString().ToUpper()));
Or by using the fluent configuration API:
Audit.Core.Configuration.Setup()
.UseAzureCosmos(config => config
.Endpoint("https://mycompany.documents.azure.com:443/")
.AuthKey("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==")
.Database("Audit")
.Container("logs")
.ClientOptions(options => { options.ConnectionMode = ConnectionMode.Gateway; }));
Mandatory config with an Endpoint and an AuthKey:
Or with a previously configured instance of DocumentClient/CosmosClient:
Container settings:
This provider implements GetEvent and GetEventAsync methods to obtain an audit event by id and partition key. Note that if your container
has a partition key defined, you need to provide both id and partition key:
var event = auditDataProvider.GetEvent(("eventId", "partitionValue"));
or using the overload on the concrete AzureCosmosDataProvider:
var event = azureCosmosDataProvider.GetEvent("eventId", "partitionValue");
The Azure Cosmos data provider also includes support for querying the events collection.
Use the QueryEvents() method on AzureCosmosDataProvider class to run LINQ queries against the audit events.
For example, to get the top 10 most time-consuming events for a specific machine:
IQueryable<AuditEvent> query = azureCosmosDataProvider.QueryEvents()
.Where(ev => ev.Environment.MachineName == "HP")
.OrderByDescending(ev => ev.Duration)
.Take(10);
Also you can use the EnumerateEvents() method to run SQL-like queries. For example the previous query can be written as:
IEnumerable<AuditEvent> events = cosmosDbDataProvider.EnumerateEvents(
@"SELECT TOP 10 *
FROM c
WHERE c.Environment.MachineName = 'HP'
ORDER BY c.Duration DESC");
This post contains information about the SQL query syntax supported by Azure Document DB.
Entity Framework Extensions and Dapper Plus are major sponsors and are proud to contribute to the development of Audit.NET
Combine the power of auditing with the speed of Bulk Operations to get the best of both worlds — audit and performance.