Audit and log integration
On this page
Log categories
TAdmin supplies login, permission and user-security auditing, plus operation, backend and SQL logs. Integrate through the filters, services and projection contracts; reuse shared frontend log pages.
| Entry point | Purpose |
|---|---|
OperateLogFilter / EnableOperateLogAttribute | Mark and capture administration actions |
AdminAuditLogController | Audit queries and exports |
AdminSystemLogController | Operation, backend and SQL log APIs |
TAdminAuditLogView | Login, permission and user-security auditing |
TAdminOperateLogView / TAdminSqlLogView | Shared operation / SQL log pages |
Declare menu, query and export permissions for log endpoints. Query access does not automatically grant full export access.
Enable operation logs for an existing API
Replace DeviceApi from the business-module example with this controller, retaining its route and permission while adding descriptions and [EnableOperateLog]:
using System.ComponentModel;
using TAdmin;
using TouchSocket.Http;
using TouchSocket.WebApi;
/// <summary>演示已授权设备动作进入宿主操作日志管线。</summary>
[Description("Device catalog")]
[Router("/api/devices/[action]")]
public sealed class DeviceApi : IPluginApiServer
{
/// <summary>保留模块示例的固定返回值,以便核对请求与日志记录。</summary>
[Description("Read device codes")]
[Permission("devices:read")]
[EnableOperateLog]
[WebApi(Method = HttpMethodType.Post)]
public string[] List() => ["P-001"];
}Reuse the module’s RPC store, menus and role grants. Install OperateLogFilter on that store in the host pipeline’s order. The attribute does not start a database logger by itself. The Operate connection and administration lifecycle must also be initialized.
Call /api/devices/List as an authorized account, then check the current realm’s operation log for DeviceApi / List, account, URL and outcome. Controller and method Description attributes provide fallback labels; host-supplied localized descriptions take precedence.
ExeStatus uses exceptions, IOperResult, unified results or IOperateLogOutcome to determine success. Custom results must implement the corresponding contract; declaring a Success property alone is insufficient.
Project sensitive arguments safely
Implement IOperateLogProjection to choose which data may enter an operation log. This independent console program verifies the projection without starting the administration host. Install TAdmin and put it in Program.cs.
using System.Text.Json;
using TAdmin;
var input = new CredentialInput { DeviceCode = "P-001", Credential = "demo-private-value" };
var json = JsonSerializer.Serialize(input.CreateOperateLogProjection());
Console.WriteLine(json);
Console.WriteLine($"Contains credential: {json.Contains(input.Credential, StringComparison.Ordinal)}");
/// <summary>业务请求携带凭据,但操作日志只允许保留设备身份与是否提供凭据。</summary>
public sealed class CredentialInput : IOperateLogProjection
{
/// <summary>可以公开用于定位业务对象的设备编码。</summary>
public string DeviceCode { get; set; } = "";
/// <summary>仅供业务处理使用,不进入操作日志的原始凭据。</summary>
public string Credential { get; set; } = "";
/// <summary>返回独立安全对象,避免日志序列化整个请求。</summary>
public object CreateOperateLogProjection() => new CredentialLog
{
DeviceCode = DeviceCode,
HasCredential = !string.IsNullOrEmpty(Credential)
};
}
/// <summary>只承载允许留痕的信息,不包含凭据原文。</summary>
public sealed class CredentialLog
{
/// <summary>定位发生操作的设备。</summary>
public string DeviceCode { get; set; } = "";
/// <summary>记录调用方是否提供凭据,不记录其内容。</summary>
public bool HasCredential { get; set; }
}Expected output:
{"DeviceCode":"P-001","HasCredential":true}
Contains credential: FalseThe filter applies projections to arguments and results before serialization and sensitive-field processing. [SkipOperateLogArg] omits both argument and return content while retaining the action and outcome.
Query and retention budgets
Default configuration:
{
"AdminLogOptions": {
"MaxPageSize": 500,
"MaxExportRows": 100000,
"OperateLogDaysAgo": 30,
"BackendLogDaysAgo": 30,
"SqlLogDaysAgo": 30,
"AuditLogDaysAgo": 30
},
"AdminLogQueueOptions": {
"Capacity": 20000,
"ShutdownFlushSeconds": 10
}
}Retention values of 0 or -1 disable age-based deletion. Corresponding MaxRowCount settings can still cap capacity independently.
| Option | Meaning and accepted range |
|---|---|
MaxPageSize | Maximum rows per page, 1–5000, default 500 |
MaxExportRows | Export row limit, 1–1000000, default 100000 |
Each *LogDaysAgo | Retention days: -1, 0 or positive up to 36500, default 30 |
Each *LogMaxRowCount | Row limit, 0–10000000; 0 disables it, independently of age cleanup |
Capacity | Queued plus in-flight records per logger, 100–1000000, default 20000 |
ShutdownFlushSeconds | Flush wait in seconds, 1–120, default 10 |
AdminLogQueueOptions exposes capacity and flush timeout, without configurable batch size or retry attempts.
Bounded async queues
Resolve TAdmin.Log.IAdminLogQueueMetrics from the initialized host container and call GetSnapshots(). Each queue reports current and process-cumulative values, rather than a database record total. There is no retry-count field.
| Snapshot field | Meaning |
|---|---|
QueueName | Stable name such as admin.log.operate, admin.log.sql or admin.log.backend |
Queued | Records waiting to be dequeued, excluding in-flight batches |
Written | Cumulative successfully written records |
WriteFailures | Cumulative failed database batch writes, rather than failed record count |
Dropped | Cumulative final discards, including capacity rejection, write failure and tenant retirement |
Full queues reject records and increment dropped counts. The current implementation finishes attempted failed groups and records failures and discards; it does not promise automatic retries or durable replay. FlushAsync completion means the relevant accepted records have finished processing, not that every record reached the database. Queued = 0 can coexist with in-flight writes. Read it alongside Written, WriteFailures and Dropped.
Shutdown flushing is limited by ShutdownFlushSeconds and database cancellation behavior.
Diagnose missing logs
| Symptom | Check in order |
|---|---|
| Successful API but no operation record | Method attribute, filter on the actual store, initialized Operate connection |
| Action present but input/output empty | SkipOperateLogArg, null projection or serialization failure |
| Growing queue | Connection health, write latency and target throughput; increasing Capacity alone is insufficient |
Rising WriteFailures / Dropped | Database failures, capacity rejection and tenant lifetime; completed flushing does not prove persistence |
| Records absent in another realm | Captured record ownership, queried realm and request identity at the time |
Data boundaries
Arguments, SQL parameters and exceptions can contain passwords, credentials or business data. Preserve redaction and projection contracts instead of persisting entire requests or refresh tokens.
Frontend log pages require postBlob, cancellation signals and the current login scope. Discard old queries and exports after endpoint or realm changes. See Vue integration.