Audit.NET Documentation

repository·master·Indexed 25 days ago

https://github.com/thepirat000/audit.net

An extensible framework for auditing executing operations in .NET and .NET Core. It enables capturing tracking information such as user IDs, machine names, and exceptions, routing them to data providers like SQL, MongoDB, or Azure. Includes Audit.EntityFramework for automatic CRUD operation logging in Entity Framework and EF Core. Supports .NET Framework 4.6.2, .NET Standard 2.0, and .NET 6.

Tokens
66.4K
Snippets
189
Records
278
Agent score
78%

What's inside Audit.NET

  1. Explore Audit.NET extensions for various systems

    master

    Audit.NET provides a wide range of specialized extension packages to intercept and audit interactions with different .NET frameworks and systems. Depending on your technology stack, you can use these extensions to generate detailed audit logs without manually instrumenting every operation.

    Supported Systems and Extensions:

    • Web & APIs

      • Audit.AzureFunctions: Middleware for Azure Functions.
      • Audit.HttpClient: Message handler for HttpClient REST calls.
      • Audit.MVC: Action filter attributes for MVC (including ASP.NET Core).
      • Audit.WebApi: Action filter attributes or middleware for Web API (including ASP.NET Core).
      • Audit.SignalR: Intercepts SignalR and SignalR Core hub processing.
      • Audit.Grpc.Server / Audit.Grpc.Client: Interceptors for gRPC server and client calls.
      • Audit.WCF / Audit.WCF.Client: Behaviors for Windows Communication Foundation (WCF).
    • Data & Persistence

      • Audit.EntityFramework: Inherit from DbContext or IdentityDbContext for Entity Framework (EF 6 and EF 7/EF Core).
      • Audit.MongoClient: Command Event Subscriber for the MongoDB Driver.
      • Audit.FileSystem: Intercepts file system events via FileSystemWatcher.
    • Application Patterns & Background Jobs

      • Audit.DynamicProxy: Uses a proxy to audit any class without code changes.
      • Audit.MediatR: Pipeline behavior for MediatR requests.
      • Audit.Hangfire: Filter attribute for Hangfire background jobs.
  2. Audit Entity Framework operations with Audit.EntityFramework

    master

    Audit.EntityFramework automatically generates audit logs for Entity Framework (EF) and Entity Framework Core (EF Core) operations. It integrates with the EF DbContext to capture detailed information about CRUD (Create, Read, Update, Delete) operations performed on your database.

    For detailed integration guides and references, consult the official documentation at https://www.learnentityframeworkcore.com/extensions/audit-entityframework-core.

  3. Understand Data Providers in Audit.NET

    master
    A Data Provider (or Storage Provider) is a component responsible for handling how audit event data is stored or processed. It manages the persistence of audit logs once an audit event is triggered and captured, defining how the AuditEvent is saved.
  4. Core Concepts: Audit Scope and Audit Event

    master

    Audit.NET revolves around two central objects:

    • Audit Scope: Represents the scope of an audited operation. It acts as a context (capturing start time, entities, etc.) and controls the lifecycle of an AuditEvent. It is a disposable object, typically used within a using statement to ensure the audit is finalized and recorded upon exit.
    • Audit Event: An extensible container that holds the actual details of the audited operation (event type, timestamp, duration, custom fields). These are typically serialized (e.g., to JSON) and sent to a Data Provider for storage.
  5. Authenticate with Google Cloud Firestore

    master

    The Firestore provider supports several authentication methods:

    • Default Application Credentials: Works automatically if running on GCP or with environment variables configured.
    • Service Account Key File: Provide a path to a JSON credentials file using .CredentialsFromFile(path).
    • Service Account JSON String: Provide a JSON string using .CredentialsFromJson(jsonString).
    • Custom FirestoreDb Instance: Provide a pre-configured FirestoreDb instance using .FirestoreDb(firestoreDb).
    Audit.Core.Configuration.Setup()
        .UseFirestore(config => config
            .ProjectId("your-project-id")
            .CredentialsFromFile("path/to/credentials.json")
            .Collection("AuditEvents"));
    
    // Service Account JSON String
    Audit.Core.Configuration.Setup()
        .UseFirestore(config => config
            .ProjectId("your-project-id")
            .CredentialsFromJson(credentialsJsonString)
            .Collection("AuditEvents"));
    
    // Custom FirestoreDb Instance
    var firestoreDb = FirestoreDb.Create("your-project-id");
    Audit.Core.Configuration.Setup()
        .UseFirestore(config => config
            .FirestoreDb(firestoreDb)
            .Collection("AuditEvents"));
  6. Configure the RavenDB Data Provider

    master

    You can configure the RavenDB data provider during application startup by setting the Audit.Core.Configuration.DataProvider property or using the UseRavenDB fluent API method.

    Important for .NET 5.0+: Since the RavenDB C# Client depends on Newtonsoft.Json, it is highly recommended to call .JsonNewtonsoftAdapter() in your global setup to ensure proper serialization.

    Common configuration patterns include:

    • Using WithSettings to define URLs and a default database.
    • Using a function to dynamically select a database based on the AuditEvent type.
    • Providing an existing IDocumentStore instance.
    // Option 1: Direct assignment with fluent settings
    Audit.Core.Configuration.DataProvider = new RavenDbDataProvider(config => config
        .WithSettings("http://127.0.0.1:8080", "AuditEvents"));
    
    // Option 2: Global setup with Newtonsoft adapter (Recommended for .NET 5+)
    Audit.Core.Configuration.Setup()
        .JsonNewtonsoftAdapter()
        .UseRavenDB(config => config
            .WithSettings(settings => settings
                .Urls("http://127.0.0.1:8080")
                .Database(ev => "Audit_" + ev.EventType)
                .Certificate(cert)));
    
    // Option 3: Using an existing IDocumentStore
    Audit.Core.Configuration.Setup()
        .UseRavenDB(config => config
            .UseDocumentStore(new DocumentStore()
            {
                Urls = new[] {"http://127.0.0.1:8080"},
                Database = "AuditEvents"
            }));
  7. Configure the MongoDB Data Provider

    master

    You can configure the MongoDB data provider during application startup using either the static DataProvider property or the fluent configuration API. This must be done before any AuditScope is created.

    Option 1: Static Property

    Set Audit.Core.Configuration.DataProvider directly with an instance of Audit.MongoDB.Providers.MongoDataProvider.

    Option 2: Fluent API

    Use Audit.Core.Configuration.Setup().UseMongoDB(...) to configure the provider.

    Option 3: Using MongoClientSettings

    Instead of a connection string, you can provide a MongoClientSettings object for more granular control over the connection.

    // Using static property
    Audit.Core.Configuration.DataProvider = new Audit.MongoDB.Providers.MongoDataProvider()
    {
        ConnectionString = "mongodb://localhost:27017",
        Database = "Audit",
        Collection = "Event"
    };
    
    // Using Fluent API
    Audit.Core.Configuration.Setup()
        .UseMongoDB(config => config
            .ConnectionString("mongodb://localhost:27017")
            .Database("Audit")
            .Collection("Event"));
    
    // Using MongoClientSettings
    Audit.Core.Configuration.Setup()
        .UseMongoDB(config => config
            .ClientSettings(new MongoClientSettings() 
            {
                Server = new MongoServerAddress("localhost", 27017), 
                UseTls = true 
            })
            .Database("Audit")
            .Collection("Event"));