AsyncLogFileWriter.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using JetBrains.Annotations;
  8. using UnityEngine;
  9. namespace Logging
  10. {
  11. public class AsyncLogFileWriter
  12. {
  13. private readonly StreamWriter writer;
  14. public AsyncLogFileWriter(string path)
  15. {
  16. var fileInfo = new FileInfo(path);
  17. if (!fileInfo.Directory?.Exists ?? false)
  18. {
  19. fileInfo.Directory?.Create();
  20. }
  21. writer = new StreamWriter(path) {AutoFlush = true};
  22. }
  23. [Obsolete("Use WriteDataLine(values)")] //TODO
  24. public async Task WriteDataLine<T>(T xValue, IEnumerable<T> values)
  25. {
  26. await writer.WriteLineAsync($"{xValue}\t{string.Join("\t", values)}");
  27. }
  28. public async Task WriteDataLine<T>(IEnumerable<T> values)
  29. {
  30. await writer.WriteLineAsync($"{string.Join("\t", values)}");
  31. }
  32. public async Task WriteDataLines<T>(IEnumerable<IEnumerable<T>> lines)
  33. {
  34. var sb = new StringBuilder();
  35. foreach (var l in lines)
  36. {
  37. sb.Append($"{string.Join("\t", l)}\n");
  38. }
  39. await writer.WriteAsync(sb.ToString());
  40. }
  41. public void Dispose()
  42. {
  43. writer?.Close();
  44. }
  45. }
  46. }