FileLogger.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. namespace Logging
  7. {
  8. public class FileLogger
  9. {
  10. #region signleton
  11. private static Lazy<FileLogger>
  12. instance =
  13. new Lazy<FileLogger>
  14. (() => new FileLogger());
  15. public static FileLogger Instance => instance.Value;
  16. public static void DestroyInstance()
  17. {
  18. if (instance.IsValueCreated)
  19. {
  20. instance.Value.Dispose();
  21. instance =
  22. new Lazy<FileLogger>
  23. (() => new FileLogger());
  24. }
  25. }
  26. #endregion
  27. private DateTime startTimestamp;
  28. private Dictionary<string, AsyncLogFileWriter> writers;
  29. private List<ILogable> logables;
  30. private FileLogger()
  31. {
  32. startTimestamp = DateTime.Now;
  33. writers = new Dictionary<string, AsyncLogFileWriter>();
  34. logables = new List<ILogable>();
  35. }
  36. public async Task RegisterLogable(ILogable l)
  37. {
  38. logables.Add(l);
  39. var writer = new AsyncLogFileWriter($"Assets/Logs/{startTimestamp:yyyy-MM-dd_HHmmss}/log_{l.Key}.tsv");
  40. await writer.WriteDataLine(l.HeaderNames);
  41. writers[l.Key] = writer;
  42. }
  43. private async Task UpdateLog(ILogable l)
  44. {
  45. if (!writers.ContainsKey(l.Key))
  46. {
  47. throw new KeyNotFoundException($"File Logger has no Logable with key {l.Key}");
  48. }
  49. await writers[l.Key].WriteDataLines(l.BufferLines);
  50. l.ClearBuffer();
  51. }
  52. public async Task UpdateRegisteredLogs()
  53. {
  54. foreach (var l in logables)
  55. {
  56. await UpdateLog(l);
  57. }
  58. }
  59. public void Dispose()
  60. {
  61. foreach (var w in writers.Values)
  62. {
  63. w.Dispose();
  64. }
  65. writers.Clear();
  66. logables.Clear();
  67. }
  68. }
  69. }