feat: add logger
This commit is contained in:
@@ -0,0 +1,63 @@
|
|||||||
|
public enum LogLevel
|
||||||
|
{
|
||||||
|
Verbose,
|
||||||
|
Info,
|
||||||
|
Warning,
|
||||||
|
Error
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Logger
|
||||||
|
{
|
||||||
|
private readonly string _name;
|
||||||
|
private static readonly object _consoleLock = new object();
|
||||||
|
|
||||||
|
public LogLevel MinimumLevel { get; set; } = LogLevel.Verbose;
|
||||||
|
|
||||||
|
public Logger(string name)
|
||||||
|
{
|
||||||
|
_name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Verbose(string message, params object[] args) => Log(LogLevel.Verbose, ConsoleColor.DarkGray, message, args);
|
||||||
|
public void Info(string message, params object[] args) => Log(LogLevel.Info, ConsoleColor.White, message, args);
|
||||||
|
public void Warning(string message, params object[] args) => Log(LogLevel.Warning, ConsoleColor.Yellow, message, args);
|
||||||
|
public void Error(string message, params object[] args) => Log(LogLevel.Error, ConsoleColor.Red, message, args);
|
||||||
|
|
||||||
|
private void Log(LogLevel level, ConsoleColor messageColor, string template, object[] args)
|
||||||
|
{
|
||||||
|
if (level < MinimumLevel) return;
|
||||||
|
|
||||||
|
string finalMessage = template;
|
||||||
|
if (args != null && args.Length > 0)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
finalMessage = string.Format(template, args);
|
||||||
|
}
|
||||||
|
catch (FormatException)
|
||||||
|
{
|
||||||
|
finalMessage = template + " [Format Error]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
string timestamp = DateTime.Now.ToString("HH:mm:ss.fff");
|
||||||
|
string levelStr = level.ToString().ToUpper().PadRight(7);
|
||||||
|
|
||||||
|
lock (_consoleLock)
|
||||||
|
{
|
||||||
|
Console.ForegroundColor = ConsoleColor.DarkGray;
|
||||||
|
Console.Write($"[{timestamp}] ");
|
||||||
|
|
||||||
|
Console.ForegroundColor = messageColor;
|
||||||
|
Console.Write($"[{levelStr}] ");
|
||||||
|
|
||||||
|
Console.ForegroundColor = ConsoleColor.Cyan;
|
||||||
|
Console.Write($"[{_name}] ");
|
||||||
|
|
||||||
|
Console.ForegroundColor = messageColor;
|
||||||
|
Console.WriteLine(finalMessage);
|
||||||
|
|
||||||
|
Console.ResetColor();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user