SSPC-Tester/SSPCTester.UI/Services/UiLogSink.cs

36 lines
1.0 KiB
C#
Raw Normal View History

using System.Collections.ObjectModel;
using System.Windows.Threading;
namespace SSPCTester.UI.Services;
/// <summary>
/// UI 日志接收器:把日志事件投递到 UI 线程的 ObservableCollection供日志面板绑定。
/// </summary>
public sealed class UiLogSink
{
private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
public ObservableCollection<LogEntry> Entries { get; } = new();
public int MaxEntries { get; set; } = 500;
public void Add(UiLogLevel level, string message)
{
var entry = new LogEntry(DateTime.Now, level, message);
if (_dispatcher.CheckAccess()) Append(entry);
else _dispatcher.BeginInvoke(() => Append(entry));
}
private void Append(LogEntry entry)
{
Entries.Add(entry);
while (Entries.Count > MaxEntries) Entries.RemoveAt(0);
}
}
public enum UiLogLevel { Info, Success, Warning, Error }
public sealed record LogEntry(DateTime Time, UiLogLevel Level, string Message)
{
public string TimeText => Time.ToString("HH:mm:ss.fff");
}