Files
GSS2Rework/GSS2.Test/FileLogger.cs
T
2025-12-19 09:35:23 +03:00

47 lines
1.7 KiB
C#

namespace GSS2.Test;
public sealed class FileLogger : ILogger
{
private readonly string _category;
private readonly string _filePath;
private static readonly object _lock = new();
public FileLogger(string category, string filePath)
{
_category = category;
_filePath = filePath;
}
#pragma warning disable CS8633 // Nullability in constraints for type parameter doesn't match the constraints for type parameter in implicitly implemented interface method'.
public IDisposable? BeginScope<TState>(TState state) => null;
#pragma warning restore CS8633 // Nullability in constraints for type parameter doesn't match the constraints for type parameter in implicitly implemented interface method'.
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
var level = logLevel switch
{
LogLevel.Trace => "TRACE",
LogLevel.Debug => "DEBUG",
LogLevel.Information => "INFO",
LogLevel.Warning => "WARN",
LogLevel.Error => "ERROR",
LogLevel.Critical => "CRIT",
_ => "NONE",
};
var message = formatter(state, exception);
var line = $"[{timestamp}] [{level}] [{_category}] [{eventId.Id}] [{eventId.Name}] {message}";
lock (_lock)
{
File.AppendAllText(_filePath, line + Environment.NewLine);
if (exception != null)
File.AppendAllText(_filePath, exception + Environment.NewLine);
}
}
}