LogWriter.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEditor.DeploymentTargets;
  5. using UnityEditor.Utils;
  6. using UnityEngine;
  7. namespace UnityEditor.TestTools.TestRunner.CommandLineTest
  8. {
  9. internal class LogWriter : IDisposable
  10. {
  11. private string m_LogsDirectory;
  12. private string m_DeviceID;
  13. private Dictionary<string, StreamWriter> m_LogStreams;
  14. private DeploymentTargetLogger m_Logger;
  15. internal LogWriter(string logsDirectory, string deviceID, DeploymentTargetLogger logger)
  16. {
  17. m_LogStreams = new Dictionary<string, StreamWriter>();
  18. m_Logger = logger;
  19. m_LogsDirectory = logsDirectory;
  20. m_DeviceID = deviceID;
  21. logger.logMessage += WriteLogToFile;
  22. }
  23. private void WriteLogToFile(string id, string logLine)
  24. {
  25. StreamWriter logStream;
  26. var streamExists = m_LogStreams.TryGetValue(id, out logStream);
  27. if (!streamExists)
  28. {
  29. var filePath = GetLogFilePath(m_LogsDirectory, m_DeviceID, id);
  30. logStream = CreateLogFile(filePath);
  31. m_LogStreams.Add(id, logStream);
  32. }
  33. try
  34. {
  35. if (logLine != null)
  36. logStream.WriteLine(logLine);
  37. }
  38. catch (Exception ex)
  39. {
  40. Debug.LogError($"Writing {id} log failed.");
  41. Debug.LogException(ex);
  42. }
  43. }
  44. public void Stop()
  45. {
  46. m_Logger.Stop();
  47. foreach (var logStream in m_LogStreams)
  48. {
  49. logStream.Value.Close();
  50. }
  51. }
  52. public void Dispose()
  53. {
  54. Stop();
  55. }
  56. private StreamWriter CreateLogFile(string path)
  57. {
  58. Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, "Creating {0} device log: {1}", m_DeviceID, path);
  59. StreamWriter streamWriter = null;
  60. try
  61. {
  62. if (!Directory.Exists(path))
  63. Directory.CreateDirectory(Path.GetDirectoryName(path));
  64. streamWriter = File.CreateText(path);
  65. }
  66. catch (Exception ex)
  67. {
  68. Debug.LogError($"Creating device log {path} file failed.");
  69. Debug.LogException(ex);
  70. }
  71. return streamWriter;
  72. }
  73. private string GetLogFilePath(string lgosDirectory, string deviceID, string logID)
  74. {
  75. var fileName = "Device-" + deviceID + "-" + logID + ".txt";
  76. fileName = string.Join("_", fileName.Split(Path.GetInvalidFileNameChars()));
  77. return Paths.Combine(lgosDirectory, fileName);
  78. }
  79. }
  80. }