MossyUpdater/Services/FileLogger.cs
2025-05-31 00:06:18 +02:00

52 lines
No EOL
1.6 KiB
C#

using System.IO;
namespace MossyUpdater.Services
{
public class FileLogger : ILogger
{
private readonly string _logPath;
private readonly SemaphoreSlim _semaphore = new(1, 1);
public FileLogger()
{
var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var appFolder = Path.Combine(appDataPath, "MossyUpdater");
Directory.CreateDirectory(appFolder);
_logPath = Path.Combine(appFolder, "log.txt");
}
public async Task LogInfoAsync(string message)
{
await WriteLogAsync(LogLevel.Info, message);
}
public async Task LogWarningAsync(string message)
{
await WriteLogAsync(LogLevel.Warning, message);
}
public async Task LogErrorAsync(string message, Exception? exception = null)
{
var fullMessage = exception != null ? $"{message} - Exception: {exception}" : message;
await WriteLogAsync(LogLevel.Error, fullMessage);
}
private async Task WriteLogAsync(LogLevel level, string message)
{
await _semaphore.WaitAsync();
try
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var logEntry = $"[{timestamp}] [{level}] {message}{Environment.NewLine}";
await File.AppendAllTextAsync(_logPath, logEntry);
}
catch
{
}
finally
{
_semaphore.Release();
}
}
}
}