C# Minimal FileLogger

Date: 2022-11-21
public static class FileLogger
{
    private const string LogFile = @"C:\Temp\Logging\MyApp.log";
    private static SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);

    private static bool LogEnabled = GetLogEnabled();

    private static bool GetLogEnabled() 
    {
        var directory = Path.GetDirectoryName(LogFile);
        return Directory.Exists(directory);
    }

    private static void Log(string level, string message, Exception ex) {
        if (!LogEnabled) return;
        semaphore.Wait();
        try
        {
            var exText = ex != null ? $"{ex}\r\n" : "";
            File.AppendAllText(LogFile, $"{DateTime.Now:u} [{level}] {message}\r\n{exText}");;
        }
        finally { 
            semaphore.Release();
        }
    }

    public static void Debug(string message, Exception ex = null) => Log("DEBUG", message, ex);
    public static void Info(string message, Exception ex = null) => Log("INFO", message, ex);
    public static void Warning(string message, Exception ex = null) => Log("WARNING", message, ex);
    public static void Error(string message, Exception ex = null) => Log("ERROR", message, ex);
}

70250cookie-checkC# Minimal FileLogger