Appearance
Getting Started with GrydAudit
This guide walks you through setting up GrydAudit in your Gryd.IO application: recording, reading, and the two opt-in features, export and integrity proof.
Prerequisites
- .NET 10.0 or later
- Entity Framework Core with PostgreSQL, the supported provider (the accent-insensitive search and the daily series translate to PostgreSQL functions)
- MediatR (for CQRS queries)
- A tenant in the session: GrydAuth, or
AddGrydTenancy()(every read is restricted to the session's tenant)
Installation
Option 1: Meta-package (Recommended)
The meta-package includes the core, application, infrastructure and API packages:
bash
dotnet add package GrydAuditOption 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.APIThe export and the integrity proof are separate, opt-in packages. See Enabling the export and Enabling the integrity proof.
Configuration
1. Add Services
In your Program.cs or startup configuration:
csharp
using GrydAudit;
var builder = WebApplication.CreateBuilder(args);
// Add GrydAudit with the actual DbContextOptionsBuilder callback.
builder.Services.AddGrydAudit(options =>
{
options.UseNpgsql(builder.Configuration.GetConnectionString("AuditDb"));
if (builder.Environment.IsDevelopment())
{
options.EnableSensitiveDataLogging();
options.EnableDetailedErrors();
}
});The extension signature is AddGrydAudit(Action<DbContextOptionsBuilder>); there is no connection-string overload. The callback configures the audit context's EF provider and options.
2. Add Controllers (Optional)
If you want the REST API endpoints, reference GrydAudit.API (or the GrydAudit meta-package, which brings it on purpose). Referencing GrydAuth.Infrastructure or GrydAudit.Infrastructure alone registers the audit services and adds no audit endpoint to the host:
csharp
using GrydAudit.API;
builder.Services.AddGrydAuditApi();3. Apply Migrations
The module ships its own migrations. Apply them at startup:
csharp
await app.ApplyGrydAuditMigrationsAsync();The host does not create a migration of its own for 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; }
// The name the trail shows for this record, read when the change is collected.
public string? AuditDisplayName => Name;
}AuditDisplayName is what makes the trail readable: it is stored with the event, so a later rename does not rewrite history. Without it, the record shows its type and id. The other members of IAuditableEntity (excluded, hidden and bookkeeping properties, category) are covered in Configuration.
Step 2: Register the interceptor when automatic entity tracking is needed
AddGrydAudit() registers the audit application and persistence services. Registering the save interceptor is a separate opt-in. Add it to the service collection and attach it to the business DbContext options that should track IAuditableEntity changes:
csharp
using GrydAudit.Infrastructure;
using Microsoft.EntityFrameworkCore;
builder.Services.AddAuditInterceptor();
builder.Services.AddDbContext<AppDbContext>((services, options) =>
options.UseNpgsql(connectionString)
.AddAuditInterceptor<AppDbContext>(services));The interceptor applies only to DbContexts whose options attach it. GrydAudit's own audit context continues to persist entries through IAuditStore.
The event is written after the business change commits. A save that fails, or a transaction that is rolled back, leaves no record. Details and the limits of that guarantee are in Configuration.
Verifying Installation
Check the trail
After performing some CRUD operations, call the list route with a session that holds the read:audit-logs permission:
http
GET /api/v1/audit-logs?entityType=Product&pageSize=20
Authorization: Bearer <token of an organization session>
Accept-Language: en-USIt returns the audit trail of the session's tenant only, newest first. See Access and Tenant Isolation and the contract.
From code:
csharp
// Using MediatR; the result carries the record, or the AUDIT_LOG_NOT_FOUND error
var result = await mediator.Send(new GetAuditLogByIdQuery(auditLogId));Enabling the export (optional)
The export of the trail (CSV and PDF) is a separate package, so a host that only records and reads the trail does not take the file, job and notification modules with it. Without it the three audit-logs/exports routes answer 503 AUDIT_EXPORT_UNAVAILABLE.
bash
dotnet add package GrydAudit.ExportRegister the auxiliary modules first, then the export:
csharp
builder.Services.AddGrydFiles(builder.Configuration);
builder.Services.AddGrydJobs(options =>
{
options.JobAssemblies.Add(typeof(GrydAudit.Infrastructure.ServiceCollectionExtensions).Assembly);
});
builder.Services.AddGrydNotifications(builder.Configuration);
builder.Services.AddGrydAudit(options => options.UseNpgsql(connectionString));
builder.Services.AddGrydAuditExport(); // after AddGrydFiles, AddGrydJobs and AddGrydNotificationsDeclare the file profile the export is stored under. The host fails its start when the file module is present and the profile is missing, or when it does not allow every format the host can produce (text/csv and application/pdf):
json
{
"GrydFiles": {
"Profiles": {
"gryd.audit-export": {
"MaxSizeBytes": 67108864,
"AllowedContentTypes": [ "text/csv", "application/pdf" ],
"DefaultRetentionMode": "RetainUntil",
"DefaultRetentionDays": 1
}
}
}
}MaxSizeBytesmust be above the largest CSV (100,000 rows is in the order of tens of MB).- The file is kept for 24 hours;
DefaultRetentionDays: 1bounds a file nobody asks for again. - The limits (100,000 rows for CSV, 5,000 for PDF), the columns and the masking are in the contract (§9).
- Who can export personal data without masking: the
export:audit-logs-personal-datapermission, which theAdminrole holds by default. See LGPD & Data Protection.
Enabling the integrity proof (optional)
Each tenant's trail forms a hash chain, sealed in batches by a job and anchored outside the audit database. It is a separate package. Without it the three integrity routes answer 503 AUDIT_INTEGRITY_UNAVAILABLE and the integrity block of a record's detail is null.
bash
dotnet add package GrydAudit.Integritycsharp
builder.Services.AddGrydFiles(builder.Configuration);
builder.Services.AddGrydJobs(options =>
{
options.JobAssemblies.Add(typeof(GrydAudit.Infrastructure.ServiceCollectionExtensions).Assembly);
});
builder.Services.AddGrydAudit(options => options.UseNpgsql(connectionString));
builder.Services.AddGrydAuditIntegrity(); // after AddGrydFiles and AddGrydJobsThe anchors are JSON files, and an anchor that can expire is not a proof, so the profile must be permanent. The host fails its start otherwise:
json
{
"GrydFiles": {
"Profiles": {
"gryd.audit-integrity": {
"AllowedContentTypes": [ "application/json" ],
"DefaultRetentionMode": "Permanent"
}
}
}
}Sealing, verification and anchor options are in Configuration.
Next Steps
- Configuration Options - Customize audit behavior
- Querying Audit Logs - Learn query options
- Audit logs contract - Full HTTP API
Troubleshooting
Audit logs not being created
- Ensure entity implements
IAuditableEntity - Verify
AddGrydAudit()was called before building the app - Check that the business
DbContextattaches the interceptor - Verify the audit migrations were applied
- A change that only updates session counters (
LastLoginAt,FailedLoginAttempts) is not recorded on purpose
An entity is saved and the trail does not show it
The event is written after the commit. If the write itself fails, the interceptor logs an error and increments the gryd_audit.recording.events_lost counter (meter GrydAudit.Recording, tag reason containing only the exception type); it does not throw. AddGrydOpenTelemetry collects this meter when enabled. Other hosts must register it with AddMeter("GrydAudit.Recording"). Configure export, scraping and an alert for increments in the host. This measurement is not durable accounting and can be lost on process, listener or exporter failure; a future audit outbox is a separate delivery guarantee.
Missing user information
The author comes from IAuditContext. GrydAuth registers its HttpContextAuditContext adapter. A host without GrydAuth provides one (see Configuration).
Export or integrity routes answer 503
The package or one of the auxiliary modules is not registered in the host. See the two sections above.
Performance concerns
For high-volume applications, consider:
- Using a separate database for audit logs
- Keeping the retention window short enough for the volume (the cleanup is on by default)
- Asking for a period of at most 90 days when searching inside the changed values