CSharpHttpServer/SimpleHttpServer/Logger.cs
2024-01-09 06:05:15 +01:00

47 lines
1.6 KiB
C#

using System.Diagnostics;
namespace SimpleHttpServer;
public class Logger {
private readonly string topic;
private readonly TextWriter outWriter;
internal Logger(string topic) : this(topic, Console.Out) { }
internal Logger(string topic, TextWriter? outWriter) {
this.topic = topic;
this.outWriter = outWriter ?? Console.Out;
}
private readonly object writeLock = new object();
public void Log(string message, LogOutputLevel level) {
var fgColor = level switch {
LogOutputLevel.Debug => ConsoleColor.Gray,
LogOutputLevel.Information => ConsoleColor.White,
LogOutputLevel.Warning => ConsoleColor.Yellow,
LogOutputLevel.Error => ConsoleColor.Red,
LogOutputLevel.Fatal => ConsoleColor.Magenta,
_ => throw new NotImplementedException(),
};
lock (writeLock) {
var origColor = Console.ForegroundColor;
Console.ForegroundColor = fgColor;
outWriter.WriteLine($"[{topic}] {message}");
Console.ForegroundColor = origColor;
}
}
[Conditional("DEBUG")]
public void Debug(string message) => Log(message, LogOutputLevel.Debug);
public void Information(string message) => Log(message, LogOutputLevel.Information);
public void Warning(string message) => Log(message, LogOutputLevel.Warning);
public void Error(string message) => Log(message, LogOutputLevel.Error);
public void Fatal(string message) => Log(message, LogOutputLevel.Fatal);
}
public enum LogOutputLevel {
Debug,
Information,
Warning,
Error,
Fatal
}