Skip to content

GrydAudit Configuration ​

This guide covers the configuration options available in GrydAudit. The HTTP behavior is in the audit logs contract; this page is about what the host configures.

Basic Configuration ​

Connection String ​

Configure the audit DbContext with an EF Core options callback:

csharp
services.AddGrydAudit(options =>
    options.UseNpgsql(Configuration.GetConnectionString("AuditDb")));

The callback receives a DbContextOptionsBuilder, so provider options (retry, command timeout) and development settings go there:

csharp
services.AddGrydAudit(options =>
{
    options.UseNpgsql(connectionString, npgsql =>
    {
        npgsql.EnableRetryOnFailure(3);
        npgsql.CommandTimeout(30);
    });

    if (environment.IsDevelopment())
    {
        options.EnableSensitiveDataLogging();
        options.EnableDetailedErrors();
    }
});

PostgreSQL is the supported provider: the accent-insensitive search and the daily series translate to PostgreSQL functions. The trail may live in its own database.

Component Registration ​

AddGrydAudit registers the application and infrastructure layers. The layers can be registered separately:

csharp
services.AddGrydAuditApplication();                                              // handlers, catalog, export and integrity use cases
services.AddGrydAuditInfrastructure(options => options.UseNpgsql(connectionString)); // DbContext, repository, retention, hash chain
services.AddGrydAuditApi();                                                      // controllers

The opt-in packages add their own registrations: AddGrydAuditExport() and AddGrydAuditIntegrity().

Audit Context ​

IAuditContext supplies the author and the origin of an event.

Default HTTP Context Provider ​

When GrydAuth is composed, it registers its HttpContextAuditContext adapter for IAuditContext. It reads the user, e-mail and display name from the session claims, the tenant from the session (falling back to the ambient tenant for routines that run without a request), and the IP, user agent, correlation id and trace id from the request.

Custom Audit Context ​

Without that registration, provide an implementation:

csharp
public class CustomAuditContext : IAuditContext
{
    public Guid? UserId { get; init; }
    public string? UserEmail { get; init; }
    public Guid? TenantId { get; init; }
    public string? IpAddress { get; init; }
    public string? UserAgent { get; init; }
    public string? CorrelationId { get; init; }
    public string? TraceId { get; init; }

    // Optional (default null): the name of the author and the routine that wrote the event.
    public string? UserDisplayName { get; init; }
    public string? SystemActor { get; init; }
}

services.AddScoped<IAuditContext>(sp => /* build it from the current request */);

Routines without a person ​

A job or a hosted service has no session. Name the routine so its events read actorType = system with a systemActor:

csharp
using (_auditActorScope.BeginSystemActor("InvoiceReminderJob"))
{
    // writes made here are recorded as the system, by that routine
}

GrydJobs opens this scope for every job execution with the short class name of the job.

Names that only the handler knows ​

The interceptor never queries the database to find a name. When an entity cannot name itself (a link that only holds two ids), the handler gives the interceptor the name before saving:

csharp
_auditNameHints.Set(userRole, $"{user.FullName} ↔ {role.Name}");

IAuditNameHints is scoped to the request. The format of link names is a single rule in GrydAuth (AuditLinkName).

What the interceptor records ​

Entity members ​

IAuditableEntity is the opt-in. Every member has a default:

MemberDefaultEffect
AuditEnabledtruefalse skips the entity (conditional auditing)
AuditCategorynullStored as security or data; any other value is stored as data. GrydAuth entities return security or data
AuditDisplayNamenullThe name stored with the event (see Getting Started)
AuditExcludedPropertiesnoneLGPD exclusion: the value is never read; the field is listed as masked with no values
AuditHiddenPropertiesnoneTechnical fields of this entity: never shown, still recorded and sealed
AuditBookkeepingPropertiesnoneFields whose change alone (besides UpdatedAt/UpdatedBy) is not an event, such as last-login counters

The global hidden fields are Id, TenantId, CreatedAt, CreatedBy, UpdatedAt, UpdatedBy, IsDeleted, DeletedAt and DeletedBy. The global masked fields are Password, PasswordHash, Secret, Token, ApiKey and RefreshToken. Hidden fields are excluded from changeCount, from changedProperties and from the details; they are included in the integrity hash.

AuditInterceptorOptions ​

csharp
services.AddAuditInterceptor(options =>
{
    options.Enabled = true;                                   // default
    options.ServiceName = "GrydOrders";                       // origin shown in the trail
    options.MaxValueLength = 4000;                            // longer values are cut and flagged `truncated`
    options.ExcludedEntityTypes.Add("TemporaryEntity");
    options.MaskedProperties.Add("CardNumber");
    options.HiddenProperties.Add("RowVersion");
});

MaskedProperties and HiddenProperties start from the global sets above; adding to them keeps the defaults.

When the event is written ​

  • The interceptor collects the changes in SavingChanges, assembles the event in SavedChanges (generated keys and the values captured before the save) and persists it only after the business change is committed.
  • With an explicit transaction (BeginTransaction), the event is persisted on commit. A rollback, a failed save or an abandoned transaction discards what was collected.
  • The write goes through IAuditStore, in its own save. It is not in the business transaction: if it fails, the business change stays committed. The interceptor does not throw; it logs an error and counts the loss in the gryd_audit.recording.events_lost counter (meter GrydAudit.Recording, tag reason, containing only the exception type). AddGrydOpenTelemetry subscribes to this meter when enabled; other hosts must register it with AddMeter("GrydAudit.Recording"). Export, scraping and alert rules are configured by the host; alert on increments after routing the meter to an exporter. 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.
  • The write is idempotent by AuditEntry.Id. EfCoreAuditStore stores the record under the entry's id (the primary key), so delivering the same entry again, in SaveAsync or inside a SaveBatchAsync batch, leaves one row and does not throw; a delivery that loses a race to a concurrent one is absorbed the same way, and the other entries of the batch are still written. This is what makes an at-least-once source, such as the transactional outbox that carries the GrydFiles trail, safe: a redelivery never adds a second line to the trail or a second link to the integrity chain. An entry built without an explicit id keeps the generated one, so a caller that never repeats a delivery sees no difference.
  • Limit: the hold-until-commit works for a transaction that goes through the context's DatabaseFacade (BeginTransaction). An ambient TransactionScope, or a DbTransaction committed directly on the connection, does not raise the EF event; those saves are recorded right after the SaveChanges.
  • Events written by hand follow the same rule. The four link-request events (created, approved, rejected, expired) go through a post-commit buffer that the unit of work flushes after the commit and discards on rollback or retry. Federation, password-reset and file events are written after the commit by their auditors. Events that describe a refusal or a denial (a refused grant, a scope denial, a failed login) change nothing, so they are written at once. The platform-role auditor is the exception, on purpose: it writes the grant and revoke events before the commit and stays fail-closed, so a grant whose audit cannot be written is undone.

Sensitive Data Handling ​

Property Exclusion (LGPD/GDPR) ​

GrydAudit uses IAuditableEntity.AuditExcludedProperties to keep sensitive values out of the audit logs:

csharp
public class Customer : BaseEntity, IAuditableEntity
{
    public Guid Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Cpf { get; set; } = string.Empty;          // Sensitive
    public string CreditCardNumber { get; set; } = string.Empty; // Sensitive

    public bool AuditEnabled => true;
    public string? AuditCategory => "data";

    // These values NEVER reach audit storage; the field is listed as masked
    public IEnumerable<string> AuditExcludedProperties =>
        ["Cpf", "CreditCardNumber"];
}

The change is still recorded as "the field changed" (masked: true, both values null), so the trail shows that the field was altered without storing what it held. See LGPD & Data Protection for the exclusion rules, the masking of exports and the compliance checklist.

Data Masking (Logging) ​

For log output (not audit storage), GrydAudit integrates with SensitiveDataMasker from Gryd.Observability to mask values in structured logs.

Label catalog ​

GET /audit-logs/catalog serves translated labels. Each module contributes its own by registering an IAuditCatalogContributor (GrydAuth and GrydFiles do); the audit module does not know the other modules:

csharp
services.TryAddEnumerable(
    ServiceDescriptor.Singleton<IAuditCatalogContributor, OrdersAuditCatalogContributor>());

The contributor declares its entity types (with their visible fields and category) and its specific actions, and answers labels for a given culture, because the export renders in the language of the request that created it, after the request ended. Labels live in .resx files (neutral English, plus pt-BR and es-ES). A catalog test fails the build when a visible field of an audited entity has no label. See the contract for the fallback rules a client applies when a key is not in the catalog.

Retention ​

The trail is cleaned up automatically, on by default. These options live in ObservabilityOptions.Audit (configuration section Observability:Audit):

OptionDefaultMeaning
EnableAutomaticCleanuptrueTurns the purge on or off
RetentionDays365Records older than this are deleted. 0 or negative disables the purge, it never deletes everything
CleanupBatchSize1000Rows per batch (clamped to 1–10,000)
CleanupSchedule0 2 * * 0Cron of the GrydJobs job (Sundays 02:00 UTC)
CleanupInterval24:00:00Period of the in-process fallback
json
{
  "Observability": {
    "Audit": {
      "EnableAutomaticCleanup": true,
      "RetentionDays": 365,
      "CleanupBatchSize": 1000
    }
  }
}

The purge deletes for good

Turning the default on changed the behavior of existing hosts: a host that never set these options starts deleting records older than 365 days. Set EnableAutomaticCleanup to false to keep everything, or raise RetentionDays to the period your obligations require (LGPD Art. 16 asks for a justified period, not an unlimited one).

How it runs:

  • With GrydJobs: AuditRetentionJob (id gryd-audit.retention-purge, queue low) runs on CleanupSchedule, once per cluster. The host must list the audit infrastructure assembly in GrydJobsOptions.JobAssemblies (as for any module that ships jobs).
  • Without GrydJobs, or without the assembly listed: a hosted service purges every CleanupInterval. Never both, and never neither by accident. Without a distributed lock, two instances may purge at the same time (a delete by id is idempotent; observers may see the same cut twice).
  • Per tenant: the purger puts each tenant in session before it deletes, so the tenant filter confines every batch. Nothing uses IgnoreQueryFilters.
  • Platform events (records with no tenant) are purged by the same window, in batches, after the tenants, inside an audited system scope. A failure of that pass does not undo the tenants'.
  • Observers: IAuditRetentionObserver.OnPurgingAsync(tenantId, cut, ct) is called before each batch is deleted. The integrity proof registers one, so the hash chain knows where it now starts. Register your own to archive what is about to go. It must be idempotent for the same cut.
  • The retentionDays that the catalog announces and the window the purge applies are the same option.

Export ​

Options of the export live with the host's GrydFiles profile gryd.audit-export (see Getting Started). Fixed by the contract: the formats (csv, pdf), the limits (100,000 and 5,000 rows), the period (up to 366 days) and the 24 hours of availability.

Port (GrydAudit.Application)Adapter (GrydAudit.Export)Replace it to
IAuditExportWriter (one per format)CsvAuditExportWriter, PdfAuditExportWriterAdd a format
IAuditExportFileStoreGrydFilesAuditExportFileStoreStore elsewhere
IAuditExportSchedulerGrydJobsAuditExportSchedulerRun elsewhere
IAuditExportNotifierInAppAuditExportNotifierNotify another way

Adding a writer for a new format means the file profile must also allow its content type; the host fails its start otherwise. The file of a failed export never exists; the error is in the export's error field.

Integrity proof ​

AuditIntegrityOptions, set in code through AddGrydAuditIntegrity(options => ...) (the options are not bound to a configuration section; bind them yourself if you want them in appsettings):

OptionDefaultMeaning
SealSchedule*/5 * * * *Cron of the sealing job
SettleDelay00:00:30A record is sealed only after this long, so writes of the same instant arrive first
SealBatchSize500Records per batch (clamped to 1–5,000)
MaxBatchesPerTenant20Batches sealed per tenant per run
AnchorGrace00:15:00How long a batch without an anchor is anchorMatches: null before it counts as missing
VerifyPageSize500Page size when verifying a period

How the proof is built, so a host owner can reason about it:

  • The canonical form is versioned (canonicalVersion), covers every field and detail, hidden ones included, and does not depend on a JSON library. The hash is SHA-256(canonical + "\n" + previous hash) in lowercase hex.
  • Sealing is by batch, per tenant, without a lock: a unique index on (TenantId, Sequence) is the barrier, and the job runs once per cluster.
  • The last hash of each batch is written as a JSON file under the gryd.audit-integrity profile with retention Permanent, before the sealing is saved. A database that is rewritten consistently still disagrees with the anchors.
  • A record is pending until sealed, unverifiable when it was written before the chain existed, and never sealed in that case.
  • The retention purge records a cut mark per tenant (also anchored) before it deletes; verification starts there. A retention without a mark is itself a tamper signal.
  • Verification results are kept 7 days; the sealing job removes the expired ones.
  • Records with no tenant are not in the chain.
  • Known limit: a record committed after its settle delay may misalign the retention cut mark. Keep SettleDelay above the longest transaction that writes audited entities.

Multi-Tenancy ​

GrydAudit captures TenantId from IAuditContext: the tenant of the operation, which is the tenant of the authenticated session (ADR 0011, D18). With GrydAuth the session middleware runs inside UseGrydAuth(); a host without it sets the request's tenant after authentication:

csharp
app.UseAuthentication();
app.UseGrydTenantSession(); // The session's tenant_id claim becomes the request's tenant
app.UseAuthorization();
// Audit interceptor reads TenantId automatically

Reads go the other way: AuditDbContext restricts every read to the tenant of the session, taken from ITenantSession. Register the tenancy (GrydAuth or AddGrydTenancy() does) or no audit log will be readable. See Access and Tenant Isolation.

A system routine that opens a system scope (BeginSystemScope) is itself recorded as system_scope.used. A routine that runs often and usually has nothing to do can ask to be recorded only when it changed something (SystemScopeRecording.OnlyWhenChanged, then SystemScope.MarkChanged()); the default records every use.

Logging ​

Configure logging for audit operations:

json
{
  "Logging": {
    "LogLevel": {
      "GrydAudit": "Information",
      "GrydAudit.Infrastructure": "Warning"
    }
  }
}

At startup the retention logs whether it is on, the window, and how to turn it off.

Released under the MIT License.