ryujinx/Ryujinx/Ui/ConsoleLog.cs

88 lines
2.7 KiB
C#
Raw Normal View History

using Ryujinx.Common.Logging;
2018-04-24 18:57:39 +00:00
using System;
using System.Collections.Concurrent;
2018-04-24 18:57:39 +00:00
using System.Collections.Generic;
using System.Threading;
namespace Ryujinx
{
static class ConsoleLog
{
private static Thread _messageThread;
private static BlockingCollection<LogEventArgs> _messageQueue;
private static Dictionary<LogLevel, ConsoleColor> _logColors;
2018-04-24 18:57:39 +00:00
private static object _consoleLock;
2018-04-24 18:57:39 +00:00
static ConsoleLog()
{
_logColors = new Dictionary<LogLevel, ConsoleColor>()
2018-04-24 18:57:39 +00:00
{
{ LogLevel.Stub, ConsoleColor.DarkGray },
{ LogLevel.Info, ConsoleColor.White },
{ LogLevel.Warning, ConsoleColor.Yellow },
{ LogLevel.Error, ConsoleColor.Red }
};
_messageQueue = new BlockingCollection<LogEventArgs>();
_consoleLock = new object();
_messageThread = new Thread(() =>
{
while (!_messageQueue.IsCompleted)
{
try
{
PrintLog(_messageQueue.Take());
}
catch (InvalidOperationException)
{
// IOE means that Take() was called on a completed collection.
// Some other thread can call CompleteAdding after we pass the
// IsCompleted check but before we call Take.
// We can simply catch the exception since the loop will break
// on the next iteration.
}
}
});
_messageThread.IsBackground = true;
_messageThread.Start();
2018-04-24 18:57:39 +00:00
}
private static void PrintLog(LogEventArgs e)
2018-04-24 18:57:39 +00:00
{
string formattedTime = e.Time.ToString(@"hh\:mm\:ss\.fff");
2018-04-24 18:57:39 +00:00
string currentThread = Thread.CurrentThread.ManagedThreadId.ToString("d4");
string message = formattedTime + " | " + currentThread + " " + e.Message;
2018-04-24 18:57:39 +00:00
if (_logColors.TryGetValue(e.Level, out ConsoleColor color))
2018-04-24 18:57:39 +00:00
{
lock (_consoleLock)
2018-04-24 18:57:39 +00:00
{
Console.ForegroundColor = color;
2018-04-24 18:57:39 +00:00
Console.WriteLine(message);
2018-04-24 18:57:39 +00:00
Console.ResetColor();
}
}
else
{
Console.WriteLine(message);
2018-04-24 18:57:39 +00:00
}
}
public static void Log(object sender, LogEventArgs e)
{
if (!_messageQueue.IsAddingCompleted)
{
_messageQueue.Add(e);
}
}
2018-04-24 18:57:39 +00:00
}
}