A Small Framework To Audit
A Small Framework To Audit
Personal Open source Business Explore Pricing Blog Support This repository Sign in Sign up
thepirat000 committed on GitHub Update README.md Latest commit e6bfb06 3 days ago
README.md
Audit.NET
chat on gitter Follow 103
An extensible framework to audit executing operations in .NET including support for .NET Framework 4.5 and NetCore 1.0
(NetStandard 1.3).
Generate an audit log with evidence for reconstruction and examination of activities that have affected specific operations or
procedures.
With Audit.NET you can generate tracking information about operations being executed. It will log environmental information
such as the caller user id, machine name, method name, exceptions, including execution time and duration, and exposing an
extensible mechanism in which you can provide extra information or implement your output mechanism for the audit logs.
Extensions to log to json Files, Event Log, SQL, MongoDB, AzureBlob and DocumentDB are provided. And also extensions to
audit different systems such as EntityFramework, MVC, WebAPI and WCF. See Extensions section for more information.
Install (NuGet)
nuget v4.5.9
Contents
Usage
Output
Custom Fields and Comments
Discard option
https://github.com/thepirat000/Audit.NET 1/10
11/6/2016 GitHub - thepirat000/Audit.NET: A small framework to audit .NET object changes
Data providers
Event Creation Policy
Configuration
Extensions
Usage
Create an Audit Scope by calling the static AuditScope.Create method.
Suppose you have the following code to cancel an order that you want to audit:
To audit this operation, you can surround the code with a using block that creates an AuditScope , indicating a target object
to track:
It is not mandatory to use a using block, but it simplifies the syntax when the code to audit is on a single block,
allowing to detect exceptions and calculate the duration by implicitly saving the event on disposal.
The first parameter of the Create method is an event type name intended to identify and group the events. The second is the
delegate to obtain the object to track (target object). This object is passed as a Func<object> to allow the library inspect the
value at the beggining and at the disposal of the scope. It is not mandatory to supply a target object, pass null when you
don't want to track a specific object.
Simple logging
If you are not tracking an object, nor the duration of an event, you can use the CreateAndSave shortcut method that logs an
event immediately. For example:
Manual Saving
You can control the creation and saving logic, by creating a manual AuditScope . For example to log a pair of Start / End
method calls as a single event:
https://github.com/thepirat000/Audit.NET 2/10
11/6/2016 GitHub - thepirat000/Audit.NET: A small framework to audit .NET object changes
}
}
For more information about the EventCreationPolicy please see Event Creation Policy section.
Output
The library will generate an output ( AuditEvent ) for each operation, including:
{
"EventType": "Order:Update",
"Environment": {
"UserName": "Federico",
"MachineName": "HP",
"DomainName": "HP",
"CallingMethodName": "Audit.UnitTest.AuditTests.TestUpdate()",
"Exception": null,
"Culture": "en-GB"
},
"StartDate": "2016-08-23T11:33:14.653191-05:00",
"EndDate": "2016-08-23T11:33:23.1820786-05:00",
"Duration": 8529,
"Target": {
"Type": "Order",
"Old": {
"OrderId": "39dc0d86-d5fc-4d2e-b918-fb1a97710c99",
"Status": 2,
"OrderItems": [{
"Sku": "1002",
"Quantity": 3.0
}]
},
"New": {
"OrderId": "39dc0d86-d5fc-4d2e-b918-fb1a97710c99",
"Status": -1,
"OrderItems": null
}
}
}
Output details
The following tables describes the output fields:
AuditEvent object
StartDate DateTime Date and time when the event has started
EndDate DateTime Date and time when the event has ended
Environment object
https://github.com/thepirat000/Audit.NET 3/10
11/6/2016 GitHub - thepirat000/Audit.NET: A small framework to audit .NET object changes
Environment object
Target object
Old Object Value of the tracked object at the beginning of the event
New Object Value of the tracked object at the end of the event
For example:
You can also set Custom Fields when creating the AuditScope , by passing an anonymous object with the properties you want
as extra fields. For example:
using (var audit = AuditScope.Create("Order:Update", () => order, new { ReferenceId = orderId }))
{
order.Status = -1;
order = Db.OrderUpdate(order);
audit.Comment("Status Updated to Cancelled");
}
{
"EventType": "Order:Update",
"Environment": {
"UserName": "Federico",
"MachineName": "HP",
"DomainName": "HP",
"CallingMethodName": "Audit.UnitTest.AuditTests.TestUpdate()",
"Exception": null,
"Culture": "en-GB"
},
"Target": {
https://github.com/thepirat000/Audit.NET 4/10
11/6/2016 GitHub - thepirat000/Audit.NET: A small framework to audit .NET object changes
"Type": "Order",
"Old": {
"OrderId": "39dc0d86-d5fc-4d2e-b918-fb1a97710c99",
"Status": 2,
},
"New": {
"OrderId": "39dc0d86-d5fc-4d2e-b918-fb1a97710c99",
"Status": -1,
}
},
"ReferenceId": "39dc0d86-d5fc-4d2e-b918-fb1a97710c99", // <-- Custom Field
"Comments": ["Status Updated to Cancelled"], // <-- Comments
"StartDate": "2016-08-23T11:34:44.656101-05:00",
"EndDate": "2016-08-23T11:34:55.1810821-05:00",
"Duration": 8531
}
Discard option
The AuditScope object has a Discard() method to allow the user to discard an event under certain condition.
For example, if you want to avoid saving the audit event when an exception is thrown:
Data providers
A data provider contains the logic to handle the audit event output, where you define what to do with the audit logs.
You can use one of the data providers included or inject your own mechanism by creating a class that inherits from
AuditDataProvider , overriding the following methods:
ReplaceEvent : should update an event given its ID, this method is only called for Creation Policies Manual or
InsertOnStartReplaceOnEnd.
For example:
https://github.com/thepirat000/Audit.NET 5/10
11/6/2016 GitHub - thepirat000/Audit.NET: A small framework to audit .NET object changes
You can set a default data provider assigning the DataProvider property on the global Configuration object. For example:
Audit.Core.Configuration.Setup()
.UseCustomProvider(new MyCustomDataProvider());
You can also set the data provider per-scope, by using an appropriate overload of the AuditScope.Create method. For
example:
As an anternative to creating your own data provider class, you can define the mechanism at run time by using the
DynamicDataProvider provider. For example:
Audit.Core.Configuration.Setup()
.UseDynamicProvider(config => config
.OnInsert(ev => Console.Write(ev.ToJson())));
Insert on End: (default) The audit event is inserted when the scope is disposed.
Insert on Start, Replace on End: The event (on its initial state) is inserted when the scope is created, and then the
complete event information is replaced when the scope is disposed.
Insert on Start, Insert on End: Two versions of the event are inserted, the initial when the scope is created, and the final
when the scope is disposed.
Manual: The event saving (insert/replace) should be explicitly invoked by calling the Save() method on the AuditScope .
You can set the Creation Policy per-scope, for example to explicitly set the Creation Policy to Manual:
If you don't provide a Creation Policy, the default Creation Policy configured will be used (see next section).
Configuration
Data provider
To change the default data provider, set the static property DataProvider on Audit.Core.Configuration class. This should be
done prior to the AuditScope creation, i.e. during application startup.
For example, to set your own provider as the default data provider:
If you don't specify a Data Provider, a default FileDataProvider will be used to write the events as .json files into the
current working directory.
Creation Policy
To change the default creation policy, set the static property SetCreationPolicy on Audit.Core.Configuration class. This
should be done prior to the AuditScope creation, i.e. during application startup.
Audit.Core.Configuration.CreationPolicy = EventCreationPolicy.Manual;
If you don't specify a Creation Policy, the default Insert on End will be used.
Custom Actions
You can configure Custom Actions that are executed for all the Audit Scopes in your application. This allows to globally
change the behavior and data, intercepting the scopes after they are created or before they are saved.
Call the static AddCustomAction() method on Audit.Core.Configuration class to attach a custom action.
https://github.com/thepirat000/Audit.NET 7/10
11/6/2016 GitHub - thepirat000/Audit.NET: A small framework to audit .NET object changes
The ActionType indicates when to perform the action. The allowed values are:
OnScopeCreated : When the Audit Scope is being created, before any saving. This is executed once per Audit Scope.
Alternatively to the properties/methods mentioned before, you can configure the library using a convenient Fluent API
provided by the method Audit.Core.Configuration.Setup() , this is the most straightforward way to configure the library.
For example, to set the FileLog Provider with its default settings using a Manual creation policy:
Audit.Core.Configuration.Setup()
.UseFileLogProvider()
.WithCreationPolicy(EventCreationPolicy.Manual);
Configuration examples
Audit.Core.Configuration.Setup()
.UseFileLogProvider(config => config
.DirectoryBuilder(_ => $@"C:\Logs\{DateTime.Now:yyyy-MM-dd}")
.FilenameBuilder(auditEvent => $"{auditEvent.Environment.UserName}_{DateTime.Now.Ticks}.json"));
File log provider with an InsertOnStart-ReplaceOnEnd creation policy, and a global custom field set in a custom action:
Audit.Core.Configuration.Setup()
.UseFileLogProvider(config => config
.FilenamePrefix("Event_")
.Directory(@"C:\AuditLogs\1"))
.WithCreationPolicy(EventCreationPolicy.InsertOnStartReplaceOnEnd)
.WithAction(x => x.OnScopeCreated(scope => scope.SetCustomField("ApplicationId", "MyApplication")));
Audit.Core.Configuration.Setup()
.UseEventLogProvider(config => config
.SourcePath("My Audited Application")
.LogName("Application"))
.WithCreationPolicy(EventCreationPolicy.InsertOnEnd);
Audit.Core.Configuration.Setup()
.UseDynamicProvider(config => config
.OnInsert(ev => Console.WriteLine("{0}: {1}->{2}", ev.StartDate, ev.Environment.UserName, ev.EventType)));
Extensions
https://github.com/thepirat000/Audit.NET 8/10
11/6/2016 GitHub - thepirat000/Audit.NET: A small framework to audit .NET object changes
The following packages are extensions to log interactions with different systems such as MVC, WebApi, WCF and Entity
Framework:
Audit.WCF
Generate detailed server-side audit logs for Windows Communication Foundation (WCF) service calls, by configuring a
provided behavior.
Audit.EntityFramework
Generate detailed audit logs for CRUD operations on Entity Framework, by inheriting from a provided DbContext .
Includes support for EF 6 and EF 7 (EF Core).
Audit.WebApi
Generate detailed audit logs by decorating Web API Methods and Controllers with an action filter attribute. Includes
support for ASP.NET Core.
Audit.MVC
Generate detailed audit logs by decorating MVC Actions and Controllers with an action filter attribute. Includes support
for ASP.NET Core MVC.
Audit.DynamicProxy
Generate detailed audit logs for any class without changing its code by using a proxy.
Storage providers
Apart from the FileLog, EventLog and Dynamic event storage providers, there are others included in different packages:
Audit.NET.SqlServer
Audit.NET.MongoDB
Store the events in a Mongo DB Collection, in BSON format.
Audit.NET.AzureDocumentDB
Audit.NET.AzureStorage
https://github.com/thepirat000/Audit.NET 9/10
11/6/2016 GitHub - thepirat000/Audit.NET: A small framework to audit .NET object changes
Audit.NET.AzureStorage
2016 GitHub, Inc. Terms Privacy Security Status Help Contact GitHub API Training Shop Blog About
https://github.com/thepirat000/Audit.NET 10/10