using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Tango.Logging { /// /// Represents stand-alone visual console emulation logger. /// /// public class ConsoleLogger : ILogger { private bool _consoleOpened; private String _consoleTitle; private ConsoleWindow console; /// /// Gets or sets a value indicating whether this is enabled. /// public bool Enabled { get; set; } /// /// Initializes a new instance of the class. /// public ConsoleLogger(String consoleTitle) { _consoleTitle = consoleTitle; Enabled = true; } /// /// Called when a new library trace is available. /// /// The output. public void OnLog(LogItemBase output) { EnsureConsoleOpen(() => { switch (output.Category) { case LogCategory.Info: console.SetColor(ConsoleColor.White); break; case LogCategory.Warning: console.SetColor(ConsoleColor.Yellow); break; case LogCategory.Error: console.SetColor(ConsoleColor.Red); break; case LogCategory.Critical: console.SetColor(ConsoleColor.DarkRed); break; case LogCategory.Debug: console.SetColor(ConsoleColor.Gray); break; } console.WriteLine(output.ToString()); }); } /// /// Waits until user closes the console. /// /// public async Task WaitForConsoleExit() { if (console != null) { await console.WaitForUserClose(); } } /// /// Ensures the console is open. /// private void EnsureConsoleOpen(Action post) { if (!_consoleOpened) { Thread t = new Thread(() => { console = new ConsoleWindow(); console.Title += " - " + _consoleTitle; _consoleOpened = true; console.Show(); console.Closed += (sender2, e2) => console.Dispatcher.InvokeShutdown(); System.Windows.Threading.Dispatcher.Run(); }); t.IsBackground = true; t.SetApartmentState(ApartmentState.STA); t.Start(); } while (!_consoleOpened) { Thread.Sleep(10); } post(); } } }