From 6336c95959ad5cf3d9672131bff0ca1a541f1bc4 Mon Sep 17 00:00:00 2001 From: Thorsten Sommer Date: Tue, 13 Jan 2026 17:48:51 +0100 Subject: [PATCH] Buffered early log events until RustService is set --- .../Tools/TerminalLogger.cs | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/app/MindWork AI Studio/Tools/TerminalLogger.cs b/app/MindWork AI Studio/Tools/TerminalLogger.cs index ed05222a..9da2c5a9 100644 --- a/app/MindWork AI Studio/Tools/TerminalLogger.cs +++ b/app/MindWork AI Studio/Tools/TerminalLogger.cs @@ -1,3 +1,5 @@ +using System.Collections.Concurrent; + using AIStudio.Tools.Services; using Microsoft.Extensions.Logging.Abstractions; @@ -11,6 +13,9 @@ public sealed class TerminalLogger() : ConsoleFormatter(FORMATTER_NAME) private static RustService? RUST_SERVICE; + // Buffer for early log events before RustService is available + private static readonly ConcurrentQueue EARLY_LOG_BUFFER = new(); + // ANSI color codes for log levels private const string ANSI_RESET = "\x1b[0m"; private const string ANSI_GRAY = "\x1b[90m"; // Trace, Debug @@ -19,12 +24,25 @@ public sealed class TerminalLogger() : ConsoleFormatter(FORMATTER_NAME) private const string ANSI_RED = "\x1b[91m"; // Error, Critical /// - /// Sets the Rust service for logging events. + /// Sets the Rust service for logging events and flushes any buffered early log events. /// /// The Rust service instance. public static void SetRustService(RustService service) { RUST_SERVICE = service; + + // Flush all buffered early log events to Rust in original order + while (EARLY_LOG_BUFFER.TryDequeue(out var bufferedEvent)) + { + service.LogEvent( + bufferedEvent.Timestamp, + bufferedEvent.LogLevel, + bufferedEvent.Category, + bufferedEvent.Message, + bufferedEvent.ExceptionMessage, + bufferedEvent.StackTrace + ); + } } public override void Write(in LogEntry logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) @@ -52,9 +70,29 @@ public sealed class TerminalLogger() : ConsoleFormatter(FORMATTER_NAME) textWriter.WriteLine(); // Send log event to Rust via API (fire-and-forget): - RUST_SERVICE?.LogEvent(timestamp, logLevel, category, message, exceptionMessage, stackTrace); + if (RUST_SERVICE is not null) + { + RUST_SERVICE.LogEvent(timestamp, logLevel, category, message, exceptionMessage, stackTrace); + } + else + { + // Buffer early log events until RustService is available + EARLY_LOG_BUFFER.Enqueue(new BufferedLogEvent(timestamp, logLevel, category, message, exceptionMessage, stackTrace)); + } } + /// + /// Represents a buffered log event for early logging before RustService is available. + /// + private readonly record struct BufferedLogEvent( + string Timestamp, + string LogLevel, + string Category, + string Message, + string? ExceptionMessage, + string? StackTrace + ); + private static string GetColorForLogLevel(LogLevel logLevel) => logLevel switch { LogLevel.Trace => ANSI_GRAY,