79 lines
2.3 KiB
C#
79 lines
2.3 KiB
C#
using Firebird2D.Interfaces;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Firebird2D.Logger
|
|
{
|
|
|
|
public class GameLogger : ILogger
|
|
{
|
|
private string LogFilePath = "Logs/";
|
|
|
|
public bool LogActive { get { return _logActive; } set { _logActive = value; if (value == false) Log("Logger", LogType.Info, "Log Deactivated"); } }
|
|
|
|
private bool _logActive = true;
|
|
|
|
private FileStream? fileStream;
|
|
|
|
private readonly object _fileLock = new();
|
|
|
|
private static readonly List<GameLogger> instances = [];
|
|
|
|
public int InstanceNumber { get; private set; }
|
|
|
|
private GameLogger(int instanceNumber, string instanceName)
|
|
{
|
|
LogFilePath += $"Log_{instanceName}.txt";
|
|
InstanceNumber = instanceNumber;
|
|
Initalize();
|
|
}
|
|
|
|
public static ILogger GetNewInstance(string instanceName)
|
|
{
|
|
GameLogger instance = new(instances.Count, instanceName);
|
|
instances.Add(instance);
|
|
return instance;
|
|
}
|
|
|
|
public static ILogger GetInstance(int instanceNumber)
|
|
{
|
|
return instances[instanceNumber];
|
|
}
|
|
|
|
private void Initalize()
|
|
{
|
|
if (!Directory.Exists("Logs"))
|
|
{
|
|
Directory.CreateDirectory("Logs");
|
|
}
|
|
|
|
fileStream = File.Open(LogFilePath, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write, FileShare.Read);
|
|
|
|
lock (_fileLock)
|
|
{
|
|
AddText(fileStream, "===================" + DateTime.Now.ToString("dd.MM.yy HH:mm:ss") + "===================" + Environment.NewLine);
|
|
}
|
|
}
|
|
|
|
public void Log(string loggingInstance, LogType type, string message)
|
|
{
|
|
if (_logActive && fileStream != null)
|
|
{
|
|
lock (_fileLock)
|
|
{
|
|
AddText(fileStream, $"{DateTime.Now:HH:mm:ss} {type}: {loggingInstance} -> {message}{Environment.NewLine}");
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void AddText(FileStream fs, string value)
|
|
{
|
|
using StreamWriter writer = new(fs, Encoding.UTF8, 1024, leaveOpen: true);
|
|
writer.Write(value);
|
|
}
|
|
}
|
|
}
|