using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; namespace Logging { public class FileLogger { #region signleton private static Lazy instance = new Lazy (() => new FileLogger()); public static FileLogger Instance => instance.Value; public static void DestroyInstance() { if (instance.IsValueCreated) { instance.Value.Dispose(); instance = new Lazy (() => new FileLogger()); } } #endregion private DateTime startTimestamp; private Dictionary writers; private List logables; private FileLogger() { startTimestamp = DateTime.Now; writers = new Dictionary(); logables = new List(); } public async Task RegisterLogable(ILogable l) { logables.Add(l); var writer = new AsyncLogFileWriter($"Assets/Logs/{startTimestamp:yyyy-MM-dd_HHmmss}/log_{l.Key}.tsv"); await writer.WriteDataLine(l.HeaderNames); writers[l.Key] = writer; } private async Task UpdateLog(ILogable l) { if (!writers.ContainsKey(l.Key)) { throw new KeyNotFoundException($"File Logger has no Logable with key {l.Key}"); } await writers[l.Key].WriteDataLines(l.BufferLines); l.ClearBuffer(); } public async Task UpdateRegisteredLogs() { foreach (var l in logables) { await UpdateLog(l); } } public void Dispose() { foreach (var w in writers.Values) { w.Dispose(); } writers.Clear(); logables.Clear(); } } }