namespace System.IO
{
public enum LogLevel
{
Debug,
Info,
Warning,
Error,
Fatal
}
public static class Logging
{
private static string _logFilePath;
private static LogLevel _minLogLevel;
public static void BasicConfig(string logFilePath, LogLevel minLogLevel = LogLevel.Info)
{
_logFilePath = logFilePath;
_minLogLevel = minLogLevel;
}
public static void Log(LogLevel level, string message, Exception ex = null)
{
if (level < _minLogLevel)
{
return;
}
string logMessage = $"{DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss")} [{level}] - {message}";
if (ex != null)
{
logMessage += $" Exception: {ex.ToString()}";
}
try
{
File.AppendAllText(_logFilePath, logMessage + "\r\n");
}
catch (Exception ex2)
{
throw new Exception($"Failed to write to log file: {ex2.Message}");
}
}
public static void Debug(string message, Exception ex = null)
{
Log(LogLevel.Debug, message, ex);
}
public static void Info(string message, Exception ex = null)
{
Log(LogLevel.Info, message, ex);
}
public static void Warning(string message, Exception ex = null)
{
Log(LogLevel.Warning, message, ex);
}
public static void Error(string message, Exception ex = null)
{
Log(LogLevel.Error, message, ex);
}
public static void Fatal(string message, Exception ex = null)
{
Log(LogLevel.Fatal, message, ex);
}
}
}