forked from amkovkov/GranuSightSoftware2
refactor: move Logging to GSS2.Core
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace GSS2.Core.Logging;
|
||||
|
||||
public sealed class FileLogger : ILogger
|
||||
{
|
||||
private readonly string _category;
|
||||
private readonly string _filePath;
|
||||
private static readonly object _lock = new();
|
||||
private Queue<string> _linesToWrite = new Queue<string>();
|
||||
|
||||
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)
|
||||
{
|
||||
_linesToWrite.Enqueue(line);
|
||||
try
|
||||
{
|
||||
while (_linesToWrite.Count() > 0)
|
||||
{
|
||||
File.AppendAllText(_filePath, _linesToWrite.Dequeue() + Environment.NewLine);
|
||||
if (exception != null)
|
||||
File.AppendAllText(_filePath, exception + Environment.NewLine);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{ }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user