Orchardcore audit trail

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore audit trail is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for configuring audit trail in Orchard Core. Covers audit event recording, the content and users audit trail events, AuditTrailPart for content tracking, the audit trail admin list with its Event, Category, Details and Actions columns, admin list filters and filter cards, settings and trimming

How to use this skill

Skill file

Orchard Core Audit Trail - Prompt Templates

Configure Audit Trail and Event Tracking

You are an Orchard Core expert. Generate audit trail configurations, custom event providers, and AuditTrailPart setups for Orchard Core.

Guidelines

Enabling Audit Trail

{
  "steps": [
    {
      "name": "Feature",
      "enable": [
        "OrchardCore.AuditTrail",
        "OrchardCore.Users.AuditTrail"
      ],
      "disable": []
    }
  ]
}

Audit Trail Event Categories

| Category | Events | Description |

|----------|--------|-------------|

| Content | Created, Saved, Published, Unpublished, Removed, Cloned, Restored | Tracks content item lifecycle events. |

| User | LoggedIn, LogInFailed (off by default), LogInIsLockedOut, Enabled, Disabled, Created, Updated, Deleted, Confirmed | Tracks user authentication and account events (OrchardCore.Users.AuditTrail). |

| User | Registered, password reset events | Added when the Users Registration and Users Reset Password features are enabled. |

Audit Trail Admin List

Each row shows four regions. In the Grid layout they are columns named Event, Category, Details, and Actions; in the List layout the same shapes are placed in zones.

| Shape | SummaryAdmin (List) zone | SummaryAdminGrid column | Content |

|-------|---------------------------|---------------------------|---------|

| AuditTrailEventName_SummaryAdmin | EventName | Event | Event name badge. |

| AuditTrailEventCategory_SummaryAdmin | EventCategory | Category | Category badge. |

| AuditTrailEventMeta_SummaryAdmin | EventMeta | Details | Time, user, and event summary. |

| AuditTrailEventActions_SummaryAdmin | Actions | Actions | Event-specific buttons (View, Restore, Details). |

Override a single shape with a template such as AuditTrailEventCategory.SummaryAdmin.cshtml, or a single grid cell with AdminListCell-AuditTrail-Category.cshtml.

Audit Trail Event List Features

| Feature | Description |

|---------|-------------|

| Date Range Filter | Filter events to a specific time period (date: term). |

| Category Filter | Filter by event category (category: term, e.g. Content, User). |

| Event Filter | Filter by event name (event: term). |

| User Filters | Bare text searches the user name (username default term); userid: filters by user ID. |

| Correlation ID | id: lists every event of one correlation ID, such as one content item. |

| Sorting | Sort entries with the sort: term. |

| Version Link | Click to view the read-only editor of a content item at that version. |

| Display Text Link | Click to edit the latest version of the content item. |

| View Button | View the content item at the recorded version. |

| Restore Button | Restore a content item to a previous version (creates a draft). |

| Details Link | View detailed event information, including textual diffs for content events. |

Adding a Custom Admin List Filter

Implement IAuditTrailAdminListFilterProvider for the logic, and a DisplayDriver<AuditTrailIndexOptions> returning AuditTrailAdminFilters_Thumbnail__<Name> (view Views/Items/AuditTrailAdminFilters-<Name>.Thumbnail.cshtml) to document it in the Available Filters dialog. The pattern is the same as orchardcore-contents-admin-list-filters.

using OrchardCore.AuditTrail.Indexes;
using OrchardCore.AuditTrail.Models;
using OrchardCore.AuditTrail.Services;
using YesSql.Filters.Query;

namespace MyModule.AuditTrail;

public sealed class ModuleAuditTrailAdminListFilterProvider : IAuditTrailAdminListFilterProvider
{
    public void Build(QueryEngineBuilder<AuditTrailEvent> builder)
    {
        builder
            .WithNamedTerm("mymodule", builder => builder
                .OneCondition((val, query) =>
                    query.With<AuditTrailEventIndex>(i => i.Category == "MyModule" && i.Name == val)));
    }
}
services.AddTransient<IAuditTrailAdminListFilterProvider, ModuleAuditTrailAdminListFilterProvider>();

The card template renders only the card's inner content (title and capability icons, token, description):

@model ShapeViewModel<AuditTrailIndexOptions>
@{
    var term = Model.Value.FilterResult.FirstOrDefault(x => x.TermName == "mymodule");
}

<div class="d-flex justify-content-between align-items-center gap-2">
    <h6 class="card-title fw-semibold mb-0">@T["My module event"]</h6>
    <span class="text-primary text-nowrap">
        <i class="fa-solid fa-sm fa-minus" title="@T["Accepts a single value"]" aria-hidden="true"></i>
    </span>
</div>
<div class="mt-1"><code class="small text-nowrap">@(term?.ToString() ?? "mymodule:...")</code></div>
<p class="card-text small text-body-secondary mt-1 mb-0">@T["Filters on an event of My Module."]</p>

Attaching AuditTrailPart via Migration

using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.Data.Migration;

namespace MyModule;

public sealed class AuditTrailMigrations : DataMigration
{
    private readonly IContentDefinitionManager _contentDefinitionManager;

    public AuditTrailMigrations(IContentDefinitionManager contentDefinitionManager)
    {
        _contentDefinitionManager = contentDefinitionManager;
    }

    public async Task<int> CreateAsync()
    {
        await _contentDefinitionManager.AlterTypeDefinitionAsync("{{ContentTypeName}}", type => type
            .WithPart("AuditTrailPart", part => part
                .WithPosition("20")
            )
        );

        return 1;
    }
}

Attaching AuditTrailPart via Recipe

{
  "steps": [
    {
      "name": "ContentDefinition",
      "ContentTypes": [
        {
          "Name": "{{ContentTypeName}}",
          "DisplayName": "{{DisplayName}}",
          "ContentTypePartDefinitionRecords": [
            {
              "PartName": "AuditTrailPart",
              "Name": "AuditTrailPart",
              "Settings": {
                "ContentTypePartSettings": {
                  "Position": "20"
                }
              }
            }
          ]
        }
      ]
    }
  ]
}

Audit Trail Settings

Configure at Settings → Audit Trail:

| Setting | Description |

|---------|-------------|

| Event Recording | Enable or disable recording for specific event types. |

| Client IP Logging | When enabled, the client IP address is included in audit trail events. Requires GDPR/privacy compliance. |

| Trimming | Configure retention period for audit events. Disable trimming to keep events indefinitely. |

| Content Tab | Select which content types should have their events recorded. |

Audit Trail Settings Recipe

{
  "steps": [
    {
      "name": "Settings",
      "AuditTrailSettings": {
        "ClientIpAddressAllowed": false,
        "Categories": [
          {
            "Name": "Content",
            "Events": [
              {
                "Name": "Published",
                "Category": "Content",
                "IsEnabled": true
              }
            ]
          }
        ]
      },
      "AuditTrailTrimmingSettings": {
        "RetentionDays": 90,
        "Disabled": false
      },
      "ContentAuditTrailSettings": {
        "AllowedContentTypes": [
          "Article",
          "Page"
        ]
      }
    }
  ]
}

Registering a Custom Audit Trail Category and Events

An event is only recorded when its category and name are registered in AuditTrailOptions. The last WithEvent arguments are enableByDefault and isMandatory.

using Microsoft.Extensions.Options;
using OrchardCore.AuditTrail.Services.Models;

namespace MyModule.AuditTrail;

public sealed class MyModuleAuditTrailEventConfiguration : IConfigureOptions<AuditTrailOptions>
{
    public const string Category = "MyModule";
    public const string Exported = nameof(Exported);

    public void Configure(AuditTrailOptions options)
    {
        options.For<MyModuleAuditTrailEventConfiguration>(Category, S => S["My Module"])
            .WithEvent(Exported, S => S["Exported"], S => S["Data was exported."], true);
    }
}

public sealed class CustomAuditEvent
{
    public string Action { get; set; }
}

Recording a Custom Audit Trail Event

using MyModule.AuditTrail;
using OrchardCore.AuditTrail.Services;
using OrchardCore.AuditTrail.Services.Models;

namespace MyModule.Services;

public sealed class MyService
{
    private readonly IAuditTrailManager _auditTrailManager;

    public MyService(IAuditTrailManager auditTrailManager)
    {
        _auditTrailManager = auditTrailManager;
    }

    public async Task PerformActionAsync(string userId, string userName)
    {
        // Perform your action...

        await _auditTrailManager.RecordEventAsync(
            new AuditTrailContext<CustomAuditEvent>(
                name: MyModuleAuditTrailEventConfiguration.Exported,
                category: MyModuleAuditTrailEventConfiguration.Category,
                correlationId: "{{CorrelationId}}",
                userId: userId,
                userName: userName,
                auditTrailEventItem: new CustomAuditEvent { Action = "Export" }
            )
        );
    }
}

Altering Events Before They Are Saved

Implement IAuditTrailEventHandler (or derive from AuditTrailEventHandlerBase) to change the create context or the built AuditTrailEvent:

using OrchardCore.AuditTrail.Models;
using OrchardCore.AuditTrail.Services;
using OrchardCore.AuditTrail.Services.Models;

namespace MyModule.AuditTrail;

public sealed class CustomAuditTrailEventHandler : AuditTrailEventHandlerBase
{
    public override Task CreateAsync(AuditTrailCreateContext context)
    {
        if (context is AuditTrailCreateContext<CustomAuditEvent> customContext)
        {
            customContext.AuditTrailEventItem.Action ??= "Unknown";
        }

        return Task.CompletedTask;
    }
}

Registering the Custom Services

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OrchardCore.AuditTrail.Services;
using OrchardCore.AuditTrail.Services.Models;
using OrchardCore.Modules;

namespace MyModule;

[RequireFeatures("OrchardCore.AuditTrail")]
public sealed class AuditTrailStartup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<IConfigureOptions<AuditTrailOptions>, MyModuleAuditTrailEventConfiguration>();
        services.AddScoped<IAuditTrailEventHandler, CustomAuditTrailEventHandler>();
    }
}

To render custom details for your event on the Details page, derive a display driver from AuditTrailEventSectionDisplayDriver<CustomAuditEvent> and place a shape in the DetailAdmin display type.

Content Event Diff Tracking

The Audit Trail module tracks diffs between content versions:

Enabling Content-Specific Audit Trail

To track specific content type events:

  1. Navigate to Settings → Audit Trail → Content tab.
  2. Select the content types to track.
  3. Save the settings.

Only events for selected content types will be recorded, reducing noise in the audit log.

Upgrading from 3.x

Best Practices

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.