Files
Syntriax.Engine/Engine.Core/Debug/FileLogger.cs

47 lines
1.2 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace Engine.Core.Debug;
public class FileLogger : LoggerBase
{
public readonly string FilePath;
private readonly Queue<string> lineQueue = new();
private Task? currentWriteTask = null;
protected async override void Write(string message)
{
lineQueue.Enqueue(message);
currentWriteTask ??= WriteLogs();
}
private async Task WriteLogs()
{
while (lineQueue.TryDequeue(out string? line))
await File.AppendAllTextAsync(FilePath, $"{line}{Environment.NewLine}");
currentWriteTask = null;
}
public FileLogger(string filePath)
{
if (!filePath.EndsWith(".log"))
filePath += ".log";
FilePath = filePath;
bool isRelativePath = Path.GetFullPath(filePath).CompareTo(filePath) != 0;
if (isRelativePath)
FilePath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath));
if (Path.GetDirectoryName(FilePath) is string directoryPath)
Directory.CreateDirectory(directoryPath);
File.Open(FilePath, FileMode.Create).Close();
}
}