2
0
Tranga/Logging/LoggerBase.cs

58 lines
1.5 KiB
C#
Raw Normal View History

2023-05-20 21:47:54 +02:00
using System.Text;
namespace Logging;
public abstract class LoggerBase : TextWriter
{
public override Encoding Encoding { get; }
private TextWriter? stdOut { get; }
public LoggerBase(TextWriter? stdOut, Encoding? encoding = null)
{
this.Encoding = encoding ?? Encoding.ASCII;
this.stdOut = stdOut;
}
public void WriteLine(string caller, string? value)
2023-05-20 21:47:54 +02:00
{
value = value is null ? Environment.NewLine : string.Join(value, Environment.NewLine);
LogMessage message = new LogMessage(DateTime.Now, caller, value);
Write(message);
}
public void Write(string caller, string? value)
2023-05-20 21:47:54 +02:00
{
if (value is null)
return;
LogMessage message = new LogMessage(DateTime.Now, caller, value);
stdOut?.Write(message.ToString());
Write(message);
}
protected abstract void Write(LogMessage message);
public class LogMessage
{
public DateTime logTime { get; }
public string caller { get; }
2023-05-20 21:47:54 +02:00
public string value { get; }
public LogMessage(DateTime now, string caller, string value)
2023-05-20 21:47:54 +02:00
{
this.logTime = now;
this.caller = caller;
2023-05-20 21:47:54 +02:00
this.value = value;
}
public override string ToString()
{
2023-05-20 22:13:25 +02:00
string dateTimeString = $"{logTime.ToShortDateString()} {logTime.ToLongTimeString()}";
return $"[{dateTimeString}] {caller,-30} | {value}";
2023-05-20 21:47:54 +02:00
}
}
}