123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- 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<FileLogger>
- instance =
- new Lazy<FileLogger>
- (() => new FileLogger());
- public static FileLogger Instance => instance.Value;
- public static void DestroyInstance()
- {
- if (instance.IsValueCreated)
- {
- instance.Value.Dispose();
- instance =
- new Lazy<FileLogger>
- (() => new FileLogger());
- }
- }
- #endregion
- private DateTime startTimestamp;
- private Dictionary<string, AsyncLogFileWriter> writers;
- private List<ILogable> logables;
- private FileLogger()
- {
- startTimestamp = DateTime.Now;
- writers = new Dictionary<string, AsyncLogFileWriter>();
- logables = new List<ILogable>();
- }
- 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();
- }
- }
- }
|