perf(logging): refresh the Log Viewer once per burst, not per event

Every log event made the Log Viewer and Debug panel rebuild up to 1000
rows on the UI thread. The in-memory store now raises EntriesChanged once,
150 ms after the first event of a burst; Clear still notifies at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-10-21 21:21:25 +07:00
1 parent 6d4843465a
commit ee557ab532
2 files changed
+86 -9

No files matched your search

@@ -12,10 +12,31 @@ namespace CommandForge.Infrastructure.Logging;
/// and the DI container. <see cref="EntriesChanged"/> may fire off the UI thread —
/// consumers must marshal to the UI thread before touching UI state.
/// </summary>
public sealed class InMemoryLogStore : ILogEventSink, ILogReader
/// <remarks>
/// A burst of log events raises <see cref="EntriesChanged"/> once, shortly after the burst starts,
/// so the Log Viewer re-reads the buffer a few times a second instead of once per event.
/// </remarks>
public sealed class InMemoryLogStore : ILogEventSink, ILogReader, IDisposable
{
private const int Capacity = 1000;
private static readonly TimeSpan DefaultNotifyDelay = TimeSpan.FromMilliseconds(150);
private readonly ConcurrentQueue<LogEntry> _entries = new();
private readonly Timer _notifyTimer;
private readonly TimeSpan _notifyDelay;
private int _notifyPending;
private volatile bool _disposed;
public InMemoryLogStore()
: this(DefaultNotifyDelay)
{
}
internal InMemoryLogStore(TimeSpan notifyDelay)
{
_notifyDelay = notifyDelay;
_notifyTimer = new Timer(_ => RaiseEntriesChanged(), null, Timeout.Infinite, Timeout.Infinite);
}
/// <inheritdoc />
public event EventHandler? EntriesChanged;
@@ -29,7 +50,11 @@ public sealed class InMemoryLogStore : ILogEventSink, ILogReader
TrimTo(Capacity);
EntriesChanged?.Invoke(this, EventArgs.Empty);
// The first event of a burst arms the timer; the rest ride along with that notification.
if (!_disposed && Interlocked.Exchange(ref _notifyPending, 1) == 0)
{
_notifyTimer.Change(_notifyDelay, Timeout.InfiniteTimeSpan);
}
}
/// <inheritdoc />
@@ -43,6 +68,20 @@ public sealed class InMemoryLogStore : ILogEventSink, ILogReader
EntriesChanged?.Invoke(this, EventArgs.Empty);
}
/// <inheritdoc />
public void Dispose()
{
_disposed = true;
_notifyTimer.Dispose();
}
private void RaiseEntriesChanged()
{
// Reset before notifying: an event that lands while handlers read the buffer arms a new round.
Volatile.Write(ref _notifyPending, 0);
EntriesChanged?.Invoke(this, EventArgs.Empty);
}
private void TrimTo(int capacity)
{
var removed = true;
@@ -11,7 +11,7 @@ public sealed class InMemoryLogStoreTests
[Fact]
public void Emit_StoresStructuredEntry_WithMappedLevelAndMessage()
{
var store = new InMemoryLogStore();
using var store = new InMemoryLogStore();
store.Emit(Event(LogEventLevel.Warning, "hello"));
var entries = store.GetRecentEntries();
@@ -23,7 +23,7 @@ public sealed class InMemoryLogStoreTests
[Fact]
public void Emit_RespectsCapacity()
{
var store = new InMemoryLogStore();
using var store = new InMemoryLogStore();
for (var i = 0; i < 1100; i++)
{
store.Emit(Event(LogEventLevel.Information, $"line {i}"));
@@ -41,25 +41,63 @@ public sealed class InMemoryLogStoreTests
[InlineData(LogEventLevel.Fatal, LogLevel.Fatal)]
public void Emit_MapsSerilogLevel(LogEventLevel serilogLevel, LogLevel expected)
{
var store = new InMemoryLogStore();
using var store = new InMemoryLogStore();
store.Emit(Event(serilogLevel, "x"));
Assert.Equal(expected, store.GetRecentEntries()[0].Level);
}
[Fact]
public void EntriesChanged_FiresOnEmitAndClear_AndClearEmpties()
public void Clear_NotifiesImmediately_AndEmpties()
{
var store = new InMemoryLogStore();
using var store = new InMemoryLogStore(Timeout.InfiniteTimeSpan); // only Clear can notify
var notifications = 0;
store.Emit(Event(LogEventLevel.Information, "x"));
store.EntriesChanged += (_, _) => notifications++;
store.Emit(Event(LogEventLevel.Information, "x"));
store.Clear();
Assert.Equal(2, notifications);
Assert.Equal(1, notifications);
Assert.Empty(store.GetRecentEntries());
}
[Fact]
public async Task EntriesChanged_CoalescesABurstIntoFewNotifications()
{
using var store = new InMemoryLogStore(TimeSpan.FromMilliseconds(100));
var notifications = 0;
var notified = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
store.EntriesChanged += (_, _) =>
{
Interlocked.Increment(ref notifications);
notified.TrySetResult();
};
for (var i = 0; i < 500; i++)
{
store.Emit(Event(LogEventLevel.Information, $"line {i}"));
}
await notified.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
// One notification per 100 ms window, not one per event (the bound allows for a slow agent).
Assert.InRange(Volatile.Read(ref notifications), 1, 50);
Assert.Equal(500, store.GetRecentEntries().Count);
}
[Fact]
public async Task EntriesChanged_FiresAgainForEventsAfterANotification()
{
using var store = new InMemoryLogStore(TimeSpan.FromMilliseconds(10));
using var notifications = new SemaphoreSlim(0);
store.EntriesChanged += (_, _) => notifications.Release();
store.Emit(Event(LogEventLevel.Information, "first"));
Assert.True(await notifications.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken));
store.Emit(Event(LogEventLevel.Information, "second"));
Assert.True(await notifications.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken));
}
private static LogEvent Event(LogEventLevel level, string message)
=> new(DateTimeOffset.Now, level, exception: null, new MessageTemplateParser().Parse(message), []);
}