Skip to content

Querying Audit Logs ​

This guide covers the ways to query and retrieve audit logs in GrydAudit. The HTTP routes, with every field, parameter, limit and error code, are defined once, in the audit logs contract. This page does not repeat them: it explains how the module behaves and how to reach the same data from code.

Query Options ​

GrydAudit provides three ways to read the trail:

  1. MediatR queries - CQRS pattern for the application layer
  2. Repository - direct data access
  3. REST API - HTTP endpoints for external access

All three share one filter, AuditLogCriteria, applied by one predicate. The list, the history of a record, the activity of a person, the summary, the facets and the export count and page the same rows.

Event Time and Date Filters ​

AuditLog.Timestamp records when the audited operation occurred. The EF store preserves AuditEntry.Timestamp, so delayed or imported entries keep their original event time rather than the time they were written to storage. AuditEntry.Builder captures the default UTC timestamp when the builder is created; use WithTimestamp to supply a historical UTC event time:

csharp
using Gryd.Observability.Audit;

string orderId = "order-123";
var entry = AuditEntry.Builder("Order", orderId)
    .WithTimestamp(new DateTime(2020, 4, 15, 12, 0, 0, DateTimeKind.Utc))
    .WithChangeType(EntityChangeType.Updated)
    .Build();

Reads sort by Timestamp and then Id, newest first by default. StartDate and EndDate include their boundary timestamps (Timestamp >= StartDate and Timestamp <= EndDate). Over HTTP both must carry Z or an offset; a date without a time zone answers 400.

Access and Tenant Isolation ​

Every read returns the audit trail of the session's tenant and nothing else. This holds for the three query options above, because the restriction is a query filter on AuditDbContext, not a parameter of any query:

  • The tenant comes from ITenantSession — the tenant of the caller's session. No query, filter or HTTP parameter takes a tenant, so a caller cannot ask for another tenant's trail.
  • A log of another tenant reads as absent. GetAuditLogByIdQuery answers AUDIT_LOG_NOT_FOUND and the API 404, exactly as for an id that does not exist.
  • Logs with no tenant (TenantId null — platform events) are visible to no tenant caller.
  • With no tenant in context, nothing is visible. Over HTTP a session without a tenant answers 403 TENANT_CONTEXT_REQUIRED. A host that composes GrydAudit without multi-tenancy (no ITenantSession registered) can write audit logs but read none.

Writes are not affected: the interceptor and IAuditStore persist each entry with the tenant it carries, under any session or none.

The routes are the scoped domain audit-logs, which declares only the tenant scope. ?scope=global and ?scope=group answer 400 SCOPE_NOT_SUPPORTED; reading across tenants, or reading platform events, is not available. The domain is announced in capabilities of GET /auth/session when the session may read the trail.

The REST endpoints require the read:audit-logs permission, which GrydAuth grants to the Admin role of every tenant. Without a session they answer 401; without the permission, 403 SCOPE_FORBIDDEN.

MediatR Queries ​

List, history and activity ​

ListAuditLogsQuery serves the list, the history of a record (EntityType and EntityId set) and the activity of a person (UserId set). Filters of the same name combine with AND; the values of one repeatable filter, with OR.

csharp
var query = new ListAuditLogsQuery
{
    Search = "joao",
    EntityType = ["User"],
    ChangeType = ["Updated", "Deleted"],
    Category = ["security"],
    StartDate = "2026-10-04T03:00:00Z",
    EndDate = "2026-10-12T02:59:59Z",
    IncludeDetails = true,
    Page = 1,
    PageSize = 20
};

var result = await mediator.Send(query);

if (result.IsSuccess)
{
    foreach (var item in result.Data!.Page.Items)
    {
        Console.WriteLine($"{item.Timestamp:u} {item.Action} {item.Outcome} by {item.UserDisplayName ?? item.UserEmail}");
    }

    // "record" or "record,details": whether the search reached the changed values
    var searchScope = result.Data.SearchScope;
}

Validation failures come back as a failed Result with the error per field, the same shape the HTTP route answers.

Get Audit Log by ID ​

csharp
var result = await mediator.Send(new GetAuditLogByIdQuery(auditLogId));

if (result.IsSuccess)
{
    var log = result.Data!;
    Console.WriteLine($"{log.Action}: {log.EntityType} ({log.EntityId})");
    Console.WriteLine($"Integrity: {log.Integrity?.Status ?? "not kept"}");
}

Summary, facets, state and catalog ​

QueryWhat it answers
GetAuditLogSummaryQueryTotals by change type, outcome and category, and the daily series with GroupBy = "day"
GetAuditLogFacetsQueryThe values that exist in a period, with counts (kept 5 minutes in the framework cache when the host has one)
GetAuditEntityStateQueryWhat a record looked like at a date, rebuilt from the trail only
GetAuditCatalogQueryThe translated labels and the retention window

Search is a case- and accent-insensitive "contains" (translate() plus ILIKE, the same rules as the other listings of the framework), so joao finds "João". % and _ are literal, and the text is trimmed.

  • It looks into userEmail, entityId, entityType, entityDisplayName and userDisplayName.
  • It looks into the changed values only when both dates are given and the period is at most 90 days. The response header X-Audit-Search-Scope (record or record,details) tells which one happened.
  • It never matches a masked value.
  • There is no pg_trgm index: the search works without the extension. If a measurement asks for one, it is an index improvement and changes no route.

Repository Direct Access ​

For scenarios where you need direct data access:

csharp
public class AuditReportService
{
    private readonly IAuditLogRepository _repository;

    public AuditReportService(IAuditLogRepository repository)
    {
        _repository = repository;
    }

    public async Task<IReadOnlyList<AuditLog>> GetRecentChangesAsync(CancellationToken cancellationToken)
    {
        var criteria = new AuditLogCriteria
        {
            StartDate = DateTime.UtcNow.AddHours(-24),
            Categories = ["security"]
        };

        var paging = new AuditLogPaging(Page: 1, PageSize: 100, Ascending: false, IncludeDetails: false);

        var result = await _repository.SearchAsync(criteria, paging, cancellationToken);
        return result.Items;
    }
}

Repository Methods ​

MethodDescription
GetByIdAsync(id)Get a single audit log by ID
SearchAsync(criteria, paging)Search with AuditLogCriteria, one page; returns the items and the total

Every method reads inside the session's tenant (see Access and Tenant Isolation). There is no method that reads by tenant. The history of a record and the activity of a person are SearchAsync with EntityTypes/EntityId or UserIds set.

AuditLogCriteria ​

PropertyMeaning
SearchText to look for (see Search)
EntityTypes, ServiceNames, PropertyNames, Categories, Outcomes, ActionsRepeatable filters; Actions also accepts the prefix form user.*
ChangeTypesEntityChangeType values
UserIds, IncludeSystemThe author filter: these people, or also the records with no author
EntityId, CorrelationIdExact match
StartDate, EndDateInclusive UTC bounds

SearchInDetails and SearchScope are computed from the dates and the search.

REST API ​

The fourteen routes, their parameters, response shapes, limits and error codes are in the audit logs contract. The ones a reader of this page reaches first:

http
GET /api/v1/audit-logs?search=joao&entityType=User&startDate=2026-10-04T03:00:00Z&endDate=2026-10-12T02:59:59Z
GET /api/v1/audit-logs/{id}
GET /api/v1/audit-logs/entity/User/{entityId}?includeDetails=true
GET /api/v1/audit-logs/user/{userId}
GET /api/v1/audit-logs/summary?groupBy=day&timeZone=America/Sao_Paulo&startDate=...&endDate=...
GET /api/v1/audit-logs/entity/User/{entityId}/state?at=2026-10-01T12:00:00Z

Responses of the list routes are the framework's PagedResult<AuditLogItem>. Errors are application/problem+json with a code; branch on the code, not on the text. The text follows Accept-Language (pt-BR, en-US, es-ES).

Pagination ​

page starts at 1 and pageSize defaults to 20 (1–100; 1–50 with includeDetails=true). A value outside the range is a 400, not an adjustment. There is no cursor paging in this version. Order is timestamp then id, descending by default, so a page never repeats or skips records that share an instant.

Performance Tips ​

  1. Use date filters: always specify StartDate and EndDate for large datasets; the summary with a daily series requires them (up to 92 days).
  2. Keep pages small: ask for includeDetails only when the screen shows the changed fields.
  3. Use the facets to fill filter selectors instead of listing the trail.
  4. Index EntityType/EntityId: the module's migrations already create the indexes the routes use.
  5. Mind the retention window: the cleanup is on by default (see Configuration).

Audit Log Details ​

Each AuditLog contains a collection of AuditLogDetail records, one per changed field. Technical fields (Id, TenantId, the Created*/Updated*/Deleted* stamps, IsDeleted) are hidden. A sensitive field is listed with Masked = true and no values:

csharp
foreach (var detail in log.Details!)
{
    Console.WriteLine($"Property: {detail.PropertyName}");
    Console.WriteLine(detail.Masked ? "  (protected)" : $"  {detail.OldValue} -> {detail.NewValue}");
}

Released under the MIT License.