A static structured logger for the Roleplay Framework. Wraps s&box Log with a level, category and current realm string, keeps the last 300 entries in a locked queue, and raises OnEntry so an in-game diagnostics panel can refresh.
using System;
using System.Collections.Generic;
using RoleplayFramework.Core;
namespace RoleplayFramework.Diagnostics;
public enum RpLogLevel { Info, Warning, Error }
public readonly record struct RpLogEntry( DateTime TimeUtc, RpLogLevel Level, string Category, string Realm, string Message );
/// <summary>
/// Structured framework logger. Every line carries a category and the current realm, e.g.
/// <c>[rp:bootstrap|offline] Config loaded</c>. Recent entries are kept in memory for the diagnostics panel.
/// Never pass passwords, tokens or other private data as messages.
/// </summary>
public static class RpLog
{
const int Capacity = 300;
static readonly Queue<RpLogEntry> _recent = new();
/// <summary>Raised for every entry (main thread). The UI uses it to refresh.</summary>
public static event Action<RpLogEntry> OnEntry;
public static void Info( string category, string message ) => Write( RpLogLevel.Info, category, message );
public static void Warn( string category, string message ) => Write( RpLogLevel.Warning, category, message );
public static void Error( string category, string message ) => Write( RpLogLevel.Error, category, message );
public static void Write( RpLogLevel level, string category, string message )
{
var entry = new RpLogEntry( DateTime.UtcNow, level, category, RealmInfo.Describe(), message );
lock ( _recent )
{
_recent.Enqueue( entry );
while ( _recent.Count > Capacity ) _recent.Dequeue();
}
var line = $"[rp:{category}|{entry.Realm}] {message}";
switch ( level )
{
case RpLogLevel.Error: Log.Error( line ); break;
case RpLogLevel.Warning: Log.Warning( line ); break;
default: Log.Info( line ); break;
}
try { OnEntry?.Invoke( entry ); }
catch ( Exception e ) { Log.Warning( $"[rp:log] listener failed: {e.Message}" ); }
}
/// <summary>Most recent entries, oldest first, optionally at or above a level.</summary>
public static List<RpLogEntry> Recent( int max = 50, RpLogLevel minimum = RpLogLevel.Info )
{
var result = new List<RpLogEntry>();
lock ( _recent )
{
foreach ( var e in _recent )
if ( e.Level >= minimum ) result.Add( e );
}
if ( result.Count > max ) result.RemoveRange( 0, result.Count - max );
return result;
}
}