FileLogger.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  7. using Valve.VR.InteractionSystem;
  8. namespace Logging
  9. {
  10. public class FileLogger
  11. {
  12. #region signleton
  13. private static Lazy<FileLogger>
  14. instance =
  15. new Lazy<FileLogger>
  16. (() => new FileLogger());
  17. public static FileLogger Instance => instance.Value;
  18. public static void DestroyInstance()
  19. {
  20. if (instance.IsValueCreated)
  21. {
  22. instance.Value.Dispose();
  23. instance =
  24. new Lazy<FileLogger>
  25. (() => new FileLogger());
  26. }
  27. }
  28. #endregion
  29. private readonly DateTime startTimestamp;
  30. private AsyncLogFileWriter writer;
  31. private readonly List<ILogable> logables;
  32. private bool writerAvailable = false;
  33. private readonly Dictionary<string, Dictionary<long, string[]>> waitingBuffers;
  34. private FileLogger()
  35. {
  36. waitingBuffers = new Dictionary<string, Dictionary<long, string[]>>();
  37. startTimestamp = DateTime.Now;
  38. logables = new List<ILogable>();
  39. }
  40. public void RegisterLogable(ILogable l) => logables.Add(l);
  41. private IEnumerable<string> MergedHeaders()
  42. {
  43. var headers = new List<string> {"timestamp"};
  44. foreach (var l in logables)
  45. {
  46. headers.AddRange(l.HeaderNames);
  47. }
  48. return headers.ToArray();
  49. }
  50. private HashSet<long> MergeTimestamps()
  51. {
  52. var allTimestamps = new HashSet<long>();
  53. Debug.Log("--- Merging Keys ---");
  54. long minBegin = -1;
  55. long minEnd = -1;
  56. foreach (var l in logables)
  57. {
  58. var keys = l.BufferLines.Keys.ToArray();
  59. var begin = keys.Length > 0 ? keys.First() : -1;
  60. var end = keys.Length > 0 ? keys.Last() : -1;
  61. if (minBegin == -1 || begin < minBegin) minBegin = begin;
  62. if (minEnd == -1 || end < minEnd) minEnd = end;
  63. }
  64. Debug.Log($"\t{minBegin} - {minEnd}");
  65. foreach (var l in logables)
  66. {
  67. Debug.Log($"\tGenerating timestamp list for {l.Key}");
  68. var bufferLines = l.BufferLines;
  69. var timestamps = new HashSet<long>(bufferLines.Keys);
  70. var logableKey = l.Key;
  71. var hasWaiting = waitingBuffers.TryGetValue(logableKey, out var waiting);
  72. if (hasWaiting)
  73. {
  74. foreach (var waitingTs in waiting.Keys)
  75. {
  76. if (waitingTs >= minBegin && waitingTs <= minEnd)
  77. {
  78. allTimestamps.Add(waitingTs);
  79. }
  80. }
  81. }
  82. foreach (var t in timestamps)
  83. {
  84. if (t >= minBegin && t <= minEnd)
  85. {
  86. allTimestamps.Add(t);
  87. }
  88. else
  89. {
  90. //Debug.Log($"\tt = {t} not in range for {l.Key}");
  91. if (waitingBuffers.ContainsKey(l.Key))
  92. {
  93. waitingBuffers[l.Key][t] = bufferLines[t];
  94. }
  95. else
  96. {
  97. waitingBuffers[l.Key] = new Dictionary<long, string[]> {{t, bufferLines[t]}};
  98. }
  99. }
  100. }
  101. Debug.Log($"\tDone generating timestamp list for {l.Key}");
  102. }
  103. logables.ForEach(l => allTimestamps.UnionWith(l.BufferLines.Keys.Where(k => k >= minBegin && k <= minEnd)));
  104. Debug.Log("--- Done Merging Keys ---");
  105. return allTimestamps;
  106. }
  107. private IEnumerable<IEnumerable<string>> MergedLines()
  108. {
  109. var lines = new List<List<string>>();
  110. var allKeys = MergeTimestamps();
  111. Debug.Log("--- Merging Lines ---");
  112. var mergedDict = new SortedDictionary<long, List<string>>();
  113. foreach (var timestamp in allKeys)
  114. {
  115. var newItem = new List<string>();
  116. for (var index = 0; index < logables.Count; index++)
  117. {
  118. var l = logables[index];
  119. var logableKey = l.Key;
  120. var hasWaiting = waitingBuffers.TryGetValue(logableKey, out var waiting);
  121. string[] linePart;
  122. if (l.BufferLines.ContainsKey(timestamp))
  123. {
  124. linePart = l.BufferLines[timestamp];
  125. }
  126. else if (hasWaiting && waiting.ContainsKey(timestamp))
  127. {
  128. Debug.Log($"\tAdd line from waiting for key {logableKey}");
  129. linePart = waiting[timestamp];
  130. waiting.Remove(timestamp);
  131. }
  132. else
  133. {
  134. //var lastAvailableKey =
  135. l.BufferLines.Keys.Where(k => k < timestamp).DefaultIfEmpty(-1).LastOrDefault();
  136. /*linePart = lastAvailableKey >= 0
  137. ? l.BufferLines[lastAvailableKey]
  138. : new string[l.HeaderNames.ToArray().Length];*/
  139. linePart = new string[l.HeaderNames.ToArray().Length];
  140. }
  141. newItem.AddRange(linePart);
  142. }
  143. mergedDict[timestamp] = newItem;
  144. }
  145. mergedDict.ForEach(item =>
  146. {
  147. var listItem = new List<string> {item.Key.ToString("D")};
  148. listItem.AddRange(item.Value);
  149. lines.Add(listItem);
  150. });
  151. Debug.Log("--- Merged Lines ---");
  152. return lines;
  153. }
  154. public async Task UpdateRegisteredLogs()
  155. {
  156. Debug.Log("UpdateRegisteredLogs()");
  157. if (!writerAvailable)
  158. {
  159. writer = new AsyncLogFileWriter($"Assets/Logs/{startTimestamp:yyyy-MM-dd_HHmmss}.tsv");
  160. await writer.WriteDataLine(MergedHeaders());
  161. writerAvailable = true;
  162. }
  163. await writer.WriteDataLines(MergedLines());
  164. Debug.Log("Clearing Bufffers");
  165. logables.ForEach(l => l.ClearBuffer());
  166. }
  167. private void Dispose()
  168. {
  169. if (writerAvailable)
  170. {
  171. writer.Dispose();
  172. }
  173. logables.Clear();
  174. }
  175. }
  176. }