Static audit log writer for the roleplay framework. Queues admin and economy events as tab separated lines, mirrors each to RpLog, and every two seconds appends the pending lines to data/roleplay/audit/yyyy-MM-dd.log by reading the day's file, appending and rewriting it.
using System;
using System.Collections.Generic;
using System.Text;
using RoleplayFramework.Diagnostics;
namespace RoleplayFramework.Rp;
/// <summary>Append-only audit trail for admin and economy-sensitive actions: data/roleplay/audit/yyyy-MM-dd.log.</summary>
public static class Audit
{
static readonly List<string> _pending = new();
static double _lastFlush;
public static void Record( string category, string actor, string action, string detail = null )
{
var line = $"{DateTime.UtcNow:O}\t{category}\t{actor}\t{action}{(detail is null ? "" : "\t" + detail)}";
_pending.Add( line );
RpLog.Info( "audit", $"{category}: {actor} {action}{(detail is null ? "" : " - " + detail)}" );
}
public static void Tick()
{
if ( _pending.Count == 0 || RealTime.NowDouble - _lastFlush < 2 ) return;
Flush();
}
public static void Flush()
{
_lastFlush = RealTime.NowDouble;
if ( _pending.Count == 0 ) return;
try
{
var fs = FileSystem.Data;
var path = $"roleplay/audit/{DateTime.UtcNow:yyyy-MM-dd}.log";
if ( !fs.DirectoryExists( "roleplay/audit" ) ) fs.CreateDirectory( "roleplay/audit" );
var existing = fs.FileExists( path ) ? fs.ReadAllText( path ) : "";
var sb = new StringBuilder( existing );
foreach ( var l in _pending ) sb.Append( l ).Append( '\n' );
fs.WriteAllText( path, sb.ToString() );
_pending.Clear();
}
catch ( Exception e )
{
RpLog.Error( "audit", $"Failed to write audit log: {e.Message}" );
}
}
}