Skip to content

Getting Started with GrydAudit

This guide walks you through setting up GrydAudit in your Gryd.IO application.

Prerequisites

  • .NET 10.0 or later
  • Entity Framework Core
  • MediatR (for CQRS queries)

Installation

Install the meta-package that includes all components:

bash
dotnet add package GrydAudit

Option 2: Individual Packages

Install only what you need:

bash
dotnet add package GrydAudit.Core
dotnet add package GrydAudit.Infrastructure
dotnet add package GrydAudit.Application
dotnet add package GrydAudit.API

Configuration

1. Add Services

In your Program.cs or startup configuration:

csharp
using GrydAudit;

var builder = WebApplication.CreateBuilder(args);

// Add GrydAudit with connection string
builder.Services.AddGrydAudit(
    builder.Configuration.GetConnectionString("AuditDb")!);

// Or with custom DbContext configuration
builder.Services.AddGrydAudit(options =>
{
    options.UseSqlServer(connectionString);
    options.EnableSensitiveDataLogging(isDevelopment);
});

2. Add Controllers (Optional)

If you want the REST API endpoints:

csharp
using GrydAudit.API;

builder.Services.AddGrydAuditApi();

3. Run Migrations

Create and apply the audit tables migration:

bash
dotnet ef migrations add InitialAudit -c AuditDbContext -o Migrations/Audit
dotnet ef database update -c AuditDbContext

Making Entities Auditable

Step 1: Implement IAuditableEntity

csharp
using Gryd.Observability.Audit;

public class Product : IAuditableEntity
{
    public Guid Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public string? Description { get; set; }
}

Step 2: Register Interceptor

The AuditSaveChangesInterceptor is automatically registered when you call AddGrydAudit(). It intercepts all SaveChanges calls and creates audit logs for entities implementing IAuditableEntity.

Verifying Installation

Check Audit Logs

After performing some CRUD operations, verify audit logs are being created:

csharp
// Using MediatR
var logs = await mediator.Send(new GetAuditLogsByEntityQuery("Product", productId));

// Using Repository directly
var logs = await auditLogRepository.GetByEntityAsync("Product", productId);

Check API Endpoints

Navigate to /api/auditlogs/search to verify the API is working.

Next Steps

Troubleshooting

Audit logs not being created

  1. Ensure entity implements IAuditableEntity
  2. Verify AddGrydAudit() was called before building the app
  3. Check that AuditDbContext is properly configured
  4. Verify database migration was applied

Missing user information

Ensure IAuditContext is being populated from HttpContext:

csharp
services.AddScoped<IAuditContext, HttpContextAuditContext>();

Performance concerns

For high-volume applications, consider:

  • Using a separate database for audit logs
  • Implementing async audit writing
  • Setting up log retention policies

Released under the MIT License.