技术控

    今日:0| 主题:63445
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Audit.NET: A small framework to audit .NET object changes

[复制链接]
tobe3213 发表于 2016-10-6 07:29:08
478 12
Audit.NET

  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 automatically log environmental information such as the caller user id, machine name, method name, exceptions, including the execution time and duration, exposing an extensible mechanism in which you can provide extra information or implement your output mechanism for the audit logs.
   Extensions to log to Files, Event Log, SQL, MongoDB, AzureBlob and DocumentDB are provided. And also extensions to audit different systems such as EntityFramework, MVC, WebAPI and WCF. SeeExtensionssection for more information.
  Install (NuGet)

  1. PM> Install-Package Audit.NET
复制代码
Contents

  
       
  • Usage   
  • Output Details   
  • Custom Fields and Comments   
  • Discard option   
  • 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:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);
复制代码
  To audit this operation, you can surround the code with a using block that creates an AuditScope , indicating a target object to track:
  1. Order order = Db.GetOrder(orderId);
  2. using (AuditScope.Create("Order:Update", () => order))
  3. {
  4.     order.Status = -1;
  5.     order.OrderItems = null;
  6.     order = Db.OrderUpdate(order);
  7. }
复制代码
  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.
   You can create an AuditScope and reuse it on different methods, for example to log a pair of Start / End methods calls as a single event:
  1. public class SomethingThatStartsAndEnds
  2. {
  3.     private AuditScope auditScope;
  4.     public int Status { get; set; }
  5.     public void Start()
  6.     {
  7.         Status = 0;
  8.         // Create the scope
  9.         auditScope = AuditScope.Create("MyEvent", () => Status);
  10.     }
  11.     public void End()
  12.     {
  13.         Status = 1;
  14.         // Dispose the scope (will save the event)
  15.         auditScope.Dispose();  
  16.     }
  17. }
复制代码
  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.
   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:
  1. AuditScope.CreateAndSave("Event Type", new { ExtraField = "extra value" });
复制代码
  The library will generate an output ( AuditEvent ) for each operation, including:
  
       
  • Tracked object's state before and after the operation.   
  • Execution time and duration.   
  • Environment information such as user, machine, domain, locale, etc.   
  • Comments and Custom Fieldsprovided.  
  An example of the output in JSON:
  1. {
  2.     "EventType": "Order:Update",
  3.     "Environment": {
  4.         "UserName": "Federico",
  5.         "MachineName": "HP",
  6.         "DomainName": "HP",
  7.         "CallingMethodName": "Audit.UnitTest.AuditTests.TestUpdate()",
  8.         "Exception": null,
  9.         "Culture": "en-GB"
  10.     },
  11.     "StartDate": "2016-08-23T11:33:14.653191-05:00",
  12.     "EndDate": "2016-08-23T11:33:23.1820786-05:00",
  13.     "Duration": 8529,
  14.     "Target": {
  15.         "Type": "Order",
  16.         "Old": {
  17.             "OrderId": "39dc0d86-d5fc-4d2e-b918-fb1a97710c99",
  18.             "Status": 2,
  19.             "OrderItems": [{
  20.                 "Sku": "1002",
  21.                 "Quantity": 3.0
  22.             }]
  23.         },
  24.         "New": {
  25.             "OrderId": "39dc0d86-d5fc-4d2e-b918-fb1a97710c99",
  26.             "Status": -1,
  27.             "OrderItems": null
  28.         }
  29.     }
  30. }
复制代码
Output details

  The following tables describes the output fields:
  
       
  • AuditEvent object

                          Field Name       Type       Description                              EventType        string       User-defined string to group the events                    Environment         Environment        Contains information about the execution environment                    StartDate        DateTime       Date and time when the event has started                    EndDate        DateTime       Date and time when the event has ended                    Duration        integer       Duration of the event in milliseconds                    Target         Target        User-defined tracked object                    Comments        Array of strings       User-defined comments                    CustomFields        Dictionary       User-defined custom fields   
  • Environment object

                          Field Name       Type       Description                              UserName        string       Current logged user name                    MachineName        string       Executing machine name                    DomainName        string       Current user domain                    CallingMethodName        string       Calling method signature information                    Exception        string       Indicates if an Exception has been detected (NULL if no exception has been thrown)                    Culture        string       Current culture identifier   
  • Target object

                          Field Name       Type       Description                              Type        string       Tracked object type name                    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  
  Custom Fields and Comments

   The AuditScope object provides two methods to extend the event output.
  
       
  •   With SetCustomField() you can store any object as a custom field.
       
  •   With Comment() you can add textual comments to the event.
      
  For example:
  1. Order order = Db.GetOrder(orderId);
  2. using (var audit = AuditScope.Create("Order:Update", () => order))
  3. {
  4.     audit.SetCustomField("ReferenceId", orderId);
  5.     order.Status = -1;
  6.     order = Db.OrderUpdate(order);
  7.     audit.Comment("Status Updated to Cancelled");
  8. }
复制代码
The output of the previous example would be:
  1. {
  2.     "EventType": "Order:Update",
  3.     "Environment": {
  4.         "UserName": "Federico",
  5.         "MachineName": "HP",
  6.         "DomainName": "HP",
  7.         "CallingMethodName": "Audit.UnitTest.AuditTests.TestUpdate()",
  8.         "Exception": null,
  9.         "Culture": "en-GB"
  10.     },
  11.     "Target": {
  12.         "Type": "Order",
  13.         "Old": {
  14.             "OrderId": "39dc0d86-d5fc-4d2e-b918-fb1a97710c99",
  15.             "Status": 2,
  16.         },
  17.         "New": {
  18.             "OrderId": "39dc0d86-d5fc-4d2e-b918-fb1a97710c99",
  19.             "Status": -1,
  20.         }
  21.     },
  22.     "ReferenceId": "39dc0d86-d5fc-4d2e-b918-fb1a97710c99",           // <-- Custom Field
  23.     "Comments": ["Status Updated to Cancelled"],                     // <-- Comments
  24.     "StartDate": "2016-08-23T11:34:44.656101-05:00",
  25.     "EndDate": "2016-08-23T11:34:55.1810821-05:00",
  26.     "Duration": 8531
  27. }
复制代码
  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:
  1. using (var audit = AuditScope.Create("Order:Update", () => order, new { ReferenceId = orderId }))
  2. {
  3.     order.Status = -1;
  4.     order = Db.OrderUpdate(order);
  5.     audit.Comment("Status Updated to Cancelled");
  6. }
复制代码
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:
  1. using (var scope = AuditScope.Create("SomeEvent", () => someTarget))
  2. {
  3.     try
  4.     {
  5.         //some operation
  6.         Critical.Operation();
  7.     }
  8.     catch (Exception ex)
  9.     {
  10.         //If an exception is thown, discard the audit event
  11.         scope.Discard();
  12.     }
  13. }
复制代码
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 thedata providers includedor inject your own mechanism by creating a class that inherits from AuditDataProvider , overriding the following methods:
  
       
  • InsertEvent : should return a unique ID for the event.   
  • ReplaceEvent : should update an event given its ID, this method is only called forCreation Policies Manual or InsertOnStartReplaceOnEnd .  
  For example:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);0
复制代码
  To indicate the data provider to use, assign the DataProvider property on the global Configuration object. SeeConfiguration sectionfor more information. For example:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);1
复制代码
Or using the fluent API:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);2
复制代码
  As an anternative, you can define the mechanism at run time by using the DynamicDataProvider provider.
  For example:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);3
复制代码
Or using the fluent API:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);4
复制代码
Data providers included

  The Data Providers included are summarized in the following table:
              Data Provider     Package     Description      Configuration API                     FileDataProvider       Audit.NET      Store the audit logs as files. Dynamically configure the directory and path.      .UseFileLogProvider()               EventLogDataProvider       Audit.NET      Write the audit logs to the Windows EventLog.      .UseEventLogProvider()               DynamicDataProvider       Audit.NET       Dynamically change the behavior at run-time. Define Insert and a Replace actions with lambda expressions.       .UseDynamicProvider()               SqlDataProvider       Audit.NET.SqlServer       Store the events as rows in a MS SQL Table, in JSON format.       .UseSqlServer()               MongoDataProvider       Audit.NET.MongoDB       Store the events in a Mongo DB collection, in BSON format.       .UseMongoDB()               AzureDbDataProvider       Audit.NET.AzureDocumentDB       Store the events in an Azure Document DB collection, in JSON format.       .UseAzureBlobStorage()               AzureBlobDataProvider       Audit.NET.AzureStorage       Store the events in an Azure Blob Storage container, in JSON format.       .UseAzureDocumentDB()            Event Creation Policy

  The audit scope can be configured to persist the event in different ways:
  
       
  •   Insert on End:( default ) The audit event is saved when the scope is disposed.
       
  •   Insert on Start, Replace on End:The event (on its initial state) is saved when the scope is created, and then the complete event information is updated when the scope is disposed.
       
  •   Insert on Start, Insert on End:Two versions of the event are saved, 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:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);5
复制代码
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:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);1
复制代码
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.
  For example, to set the default creation policy to Manual:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);7
复制代码
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.
  For example, to globally discard the events under centain condition:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);8
复制代码
Or to add custom fields / comments globally to all scopes:
  1. Order order = Db.GetOrder(orderId);
  2. order.Status = -1;
  3. order.OrderItems = null;
  4. order = Db.OrderUpdate(order);9
复制代码
  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.   
  • OnEventSaving : When an Audit Scope's Event is about to be saved.  
  Configuration Fluent API

   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:
  1. Order order = Db.GetOrder(orderId);
  2. using (AuditScope.Create("Order:Update", () => order))
  3. {
  4.     order.Status = -1;
  5.     order.OrderItems = null;
  6.     order = Db.OrderUpdate(order);
  7. }0
复制代码
Configuration examples

  File log provider with dynamic directory path and filename (fluent API):

  1. Order order = Db.GetOrder(orderId);
  2. using (AuditScope.Create("Order:Update", () => order))
  3. {
  4.     order.Status = -1;
  5.     order.OrderItems = null;
  6.     order = Db.OrderUpdate(order);
  7. }1
复制代码
File log provider with an InsertOnStart-ReplaceOnEnd creation policy, and a global custom field set in a custom action:
  1. Order order = Db.GetOrder(orderId);
  2. using (AuditScope.Create("Order:Update", () => order))
  3. {
  4.     order.Status = -1;
  5.     order.OrderItems = null;
  6.     order = Db.OrderUpdate(order);
  7. }2
复制代码
Event log provider with an InsertOnEnd creation policy (fluent API):

  1. Order order = Db.GetOrder(orderId);
  2. using (AuditScope.Create("Order:Update", () => order))
  3. {
  4.     order.Status = -1;
  5.     order.OrderItems = null;
  6.     order = Db.OrderUpdate(order);
  7. }3
复制代码
Dynamic provider to log to the console (fluent API):

  1. Order order = Db.GetOrder(orderId);
  2. using (AuditScope.Create("Order:Update", () => order))
  3. {
  4.     order.Status = -1;
  5.     order.OrderItems = null;
  6.     order = Db.OrderUpdate(order);
  7. }4
复制代码
Extensions

  The following packages are extensions to log interactions with different systems such as MVC, WebApi, WCF and Entity Framework:
   

Audit.NET: A small framework to audit .NET object changes

Audit.NET: A small framework to audit .NET object changes

  
       
  • 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 MVC.
       
  • 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: A small framework to audit .NET object changes

Audit.NET: A small framework to audit .NET object changes

  
       
  • Audit.NET.SqlServer

    Store the events as rows in a SQL Table, in JSON format.
       
  • Audit.NET.MongoDB

    Store the events in a Mongo DB Collection, in BSON format.
       
  • Audit.NET.AzureDocumentDB

    Store the events in an Azure Document DB Collection, in JSON format.
       
  • Audit.NET.AzureStorage

    Store the events in an Azure Blob Storage container, in JSON format.
      
凌薇 发表于 2016-10-6 09:01:39
土豪,交个朋友
回复 支持 反对

使用道具 举报

亦寒 发表于 2016-10-6 10:48:00
路过的帮顶
回复 支持 反对

使用道具 举报

liushixinglive 发表于 2016-10-8 03:03:07
星期六加班的飘过
回复 支持 反对

使用道具 举报

亦旋 发表于 2016-10-18 05:57:13
你拥有再大再多的水桶,也不如有一个水龙头。说明:”渠道很重要!
回复 支持 反对

使用道具 举报

逗比 发表于 2016-10-18 09:27:34
tobe3213 顶起!
回复 支持 反对

使用道具 举报

刘鑫磊 发表于 2016-10-20 19:54:29
鸟大了什么林子都有。。
回复 支持 反对

使用道具 举报

方小雪 发表于 2016-10-23 17:30:50
不要迷恋楼主,楼主只是个传说。
回复 支持 反对

使用道具 举报

頭痛~出賣了我 发表于 2016-10-25 00:19:02
人又不聪明,还学人家秃顶!!
回复 支持 反对

使用道具 举报

lili521 发表于 2016-10-26 20:32:24
系统居然说我是在灌水,我有吗?
回复 支持 反对

使用道具 举报

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表