62 lines
2.0 KiB
C#
62 lines
2.0 KiB
C#
using System.Diagnostics;
|
|
|
|
namespace SimpleHttpServer;
|
|
public class Logger {
|
|
private readonly string topic;
|
|
private readonly LogOutputTopic ltopic;
|
|
private readonly bool printToConsole;
|
|
private readonly SimpleHttpServerConfiguration.CustomLogMessageHandler? externalLogMsgHandler;
|
|
|
|
internal Logger(LogOutputTopic topic, SimpleHttpServerConfiguration conf) {
|
|
this.topic = Enum.GetName(topic) ?? throw new ArgumentException("The given LogOutputTopic is not defined!");
|
|
ltopic = topic;
|
|
externalLogMsgHandler = conf.LogMessageHandler;
|
|
printToConsole = !conf.DisableLogMessagePrinting;
|
|
}
|
|
|
|
private readonly object writeLock = new();
|
|
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(),
|
|
};
|
|
|
|
if (printToConsole)
|
|
lock (writeLock) {
|
|
var origColor = Console.ForegroundColor;
|
|
Console.ForegroundColor = fgColor;
|
|
Console.WriteLine($"[{topic}] {message}");
|
|
Console.ForegroundColor = origColor;
|
|
}
|
|
|
|
externalLogMsgHandler?.Invoke(ltopic, message, level);
|
|
}
|
|
|
|
[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
|
|
}
|
|
|
|
public enum LogOutputTopic {
|
|
Main,
|
|
Request,
|
|
Security
|
|
}
|
|
|