Custom Console-Output with Log-Time and elapsed time, as well as routeabilty to other outputs.

This commit is contained in:
glax 2023-03-30 17:03:21 +02:00
parent cb0442d760
commit 7560d59c25

52
Server/ConsoleWriter.cs Normal file
View File

@ -0,0 +1,52 @@
using System.Globalization;
using System.Text;
namespace Server;
public class ConsoleWriter : TextWriter
{
public override Encoding Encoding { get; }
private TextWriter stdOut { get; }
private DateTime execStart { get; }
public event EventHandler<ConsoleWriterEventArgs>? OnWrite;
public event EventHandler<ConsoleWriterEventArgs>? OnWriteLine;
public ConsoleWriter()
{
stdOut = Console.Out;
execStart = DateTime.Now;
Encoding = Encoding.UTF8;
}
public ConsoleWriter(DateTime execStart)
{
stdOut = Console.Out;
this.execStart = execStart;
Encoding = Encoding.UTF8;
}
public override void WriteLine(string? text)
{
DateTime now = DateTime.Now;
string dateTimeString = $"[{now.ToUniversalTime():u} ({Math.Floor((now - execStart).TotalMilliseconds):####00000})]";
if(text is not null)
OnWriteLine?.Invoke(this, new ConsoleWriterEventArgs($"{dateTimeString} {text}"));
stdOut.WriteLine($"{dateTimeString} {text}");
}
public override void Write(string? text)
{
if(text is not null)
OnWrite?.Invoke(this, new ConsoleWriterEventArgs(text));
stdOut.Write(text);
}
}
public class ConsoleWriterEventArgs : EventArgs
{
public string text { get; }
public ConsoleWriterEventArgs(string text)
{
this.text = text;
}
}