using Serilog.Core; using Serilog.Events; using System.Windows; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Controls; namespace SharepointToolbox.Infrastructure.Logging; /// /// Custom Serilog sink that writes timestamped, color-coded entries to a WPF RichTextBox. /// Format: HH:mm:ss [LEVEL] Message — green=info/success, orange=warning, red=error. /// All writes dispatch to the UI thread via Application.Current.Dispatcher. /// public class LogPanelSink : ILogEventSink { private readonly RichTextBox _richTextBox; public LogPanelSink(RichTextBox richTextBox) { _richTextBox = richTextBox; } public void Emit(LogEvent logEvent) { var message = logEvent.RenderMessage(); var timestamp = logEvent.Timestamp.ToString("HH:mm:ss"); var level = logEvent.Level.ToString().ToUpperInvariant()[..4]; // INFO, WARN, ERRO, FATL var text = $"{timestamp} [{level}] {message}"; var color = GetColor(logEvent.Level); Application.Current?.Dispatcher.InvokeAsync(() => { var para = new Paragraph(new Run(text) { Foreground = new SolidColorBrush(color) }) { Margin = new Thickness(0) }; _richTextBox.Document.Blocks.Add(para); _richTextBox.ScrollToEnd(); }); } private static Color GetColor(LogEventLevel level) => level switch { LogEventLevel.Warning => Colors.Orange, LogEventLevel.Error or LogEventLevel.Fatal => Colors.Red, _ => Colors.LimeGreen }; }