Add logging functionality with ILogger interface and implementations
This commit is contained in:
73
GameCore/Logging/FileLogger.cs
Normal file
73
GameCore/Logging/FileLogger.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
using System.Text;
|
||||
using GameCore.Logging.Interfaces;
|
||||
|
||||
namespace GameCore.Logging;
|
||||
|
||||
public class FileLogger : ILogger, IDisposable
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
private readonly LogLevel _minLogLevel = LogLevel.Debug;
|
||||
private readonly StreamWriter _streamWriter;
|
||||
|
||||
public FileLogger(string filePath, LogLevel minLogLevel = LogLevel.Debug)
|
||||
{
|
||||
_minLogLevel = minLogLevel;
|
||||
|
||||
var stream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read);
|
||||
_streamWriter = new StreamWriter(stream, Encoding.UTF8);
|
||||
_streamWriter.AutoFlush = true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public void Debug(string message)
|
||||
{
|
||||
Log(LogLevel.Debug, message);
|
||||
}
|
||||
|
||||
public void Info(string message)
|
||||
{
|
||||
Log(LogLevel.Info, message);
|
||||
}
|
||||
|
||||
public void Warn(string message)
|
||||
{
|
||||
Log(LogLevel.Warn, message);
|
||||
}
|
||||
|
||||
public void Error(string message, Exception? ex = null)
|
||||
{
|
||||
Log(LogLevel.Error, message, ex);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
lock (_lock)
|
||||
{
|
||||
_streamWriter?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
~FileLogger()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
|
||||
private void Log(LogLevel level, string message, Exception? ex = null)
|
||||
{
|
||||
if (level < _minLogLevel) return;
|
||||
|
||||
var logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffff}] [{level.ToString().ToUpper()}] {message}";
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
_streamWriter.WriteLine(logMessage);
|
||||
if (ex != null) _streamWriter.WriteLine(ex.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user