OSMServer/Server/ConsoleWriter.cs

53 lines
1.4 KiB
C#
Raw Normal View History

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;
2023-04-01 18:08:31 +02:00
string dateTimeString = $"[{now.ToUniversalTime():u} ({Math.Floor((now - execStart).TotalMilliseconds):###,###,###})]";
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;
}
}