using Discord;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace RMSoftware.ModularBot
{
public class ConsoleLogWriter
{
bool WriterBusy = false;
Stack<LogMessage> log_stack = new Stack<LogMessage>();
public async Task WriteEntry(LogMessage message)
{
string category = message.Source;
string logText = message.Message;
if (WriterBusy)//If busy, queue it up.
{
//check for item in queue.
if (log_stack.Contains(message))
{
//don't queue.
return;
}
else
{
//re-queue.
log_stack.Push(message);
}
return;
}
else //Otherwise, process it.
{
WriterBusy = true;
ConsoleColor BG = Console.BackgroundColor;
ConsoleColor FG = Console.ForegroundColor;
switch (message.Severity)
{
case LogSeverity.Critical:
BG = ConsoleColor.DarkRed;
break;
case LogSeverity.Error:
BG = ConsoleColor.Red;
break;
case LogSeverity.Warning:
BG = ConsoleColor.Yellow; FG = ConsoleColor.Black;
break;
case LogSeverity.Info:
BG = ConsoleColor.DarkBlue;
break;
case LogSeverity.Verbose:
BG = ConsoleColor.Black;
break;
case LogSeverity.Debug:
BG = ConsoleColor.Black;
break;
default:
break;
}
Console.Write(DateTime.Now.ToString("HH:mm:ss").PadRight(9));
ConsoleColor last = Console.BackgroundColor;
ConsoleColor f_last = Console.ForegroundColor;
Console.BackgroundColor = BG;
Console.ForegroundColor = FG;
if (message.Source.Length > 11)
{
Console.Write(message.Source.Substring(0, 11));
}
else
{
Console.Write(message.Source.PadRight(11));
}
Console.BackgroundColor = last;
Console.ForegroundColor = f_last;
Console.Write(" ");
Console.WriteLine(message.Message);
await Task.Delay(3);
WriterBusy = false;//after the writer is finished writing this entry, it won't be busy.
}
}
public void push(LogMessage logmessage)
{
log_stack.Push(logmessage);
}
public async Task ProcessStack()
{
while (true)
{
if(!Program.discon)
{
SpinWait.SpinUntil(() => log_stack.Count > 0);
}
//once the log stack has shit inside, process it if writer isn't busy.
if(WriterBusy)
{
return;//Do not write an entry if the writer is busy.
}
await WriteEntry(log_stack.Pop());
}
}
}
}
Comments