DiskLogListener.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.IO;
  2. using System.Text;
  3. using System.Threading;
  4. namespace BepInEx.Logging
  5. {
  6. /// <summary>
  7. /// Logs entries using Unity specific outputs.
  8. /// </summary>
  9. public class DiskLogListener : ILogListener
  10. {
  11. public LogLevel DisplayedLogLevel { get; set; }
  12. public TextWriter LogWriter { get; protected set; }
  13. public Timer FlushTimer { get; protected set; }
  14. public bool WriteFromUnityLog { get; set; }
  15. public DiskLogListener(string localPath, LogLevel displayedLogLevel = LogLevel.Info, bool appendLog = false, bool includeUnityLog = false)
  16. {
  17. WriteFromUnityLog = includeUnityLog;
  18. DisplayedLogLevel = displayedLogLevel;
  19. int counter = 1;
  20. FileStream fileStream;
  21. while (!Utility.TryOpenFileStream(Path.Combine(Paths.BepInExRootPath, localPath), appendLog ? FileMode.Append : FileMode.Create, out fileStream, share: FileShare.Read))
  22. {
  23. if (counter == 5)
  24. {
  25. Logger.LogError("Couldn't open a log file for writing. Skipping log file creation");
  26. return;
  27. }
  28. Logger.LogWarning($"Couldn't open log file '{localPath}' for writing, trying another...");
  29. localPath = $"LogOutput.log.{counter++}";
  30. }
  31. LogWriter = TextWriter.Synchronized(new StreamWriter(fileStream, Encoding.UTF8));
  32. FlushTimer = new Timer(o => { LogWriter?.Flush(); }, null, 2000, 2000);
  33. }
  34. public void LogEvent(object sender, LogEventArgs eventArgs)
  35. {
  36. if (!WriteFromUnityLog && eventArgs.Source is UnityLogSource)
  37. return;
  38. if (eventArgs.Level.GetHighestLevel() > DisplayedLogLevel)
  39. return;
  40. LogWriter.WriteLine($"[{eventArgs.Level,-7}:{((ILogSource)sender).SourceName,10}] {eventArgs.Data}");
  41. }
  42. public void Dispose()
  43. {
  44. FlushTimer?.Dispose();
  45. LogWriter?.Flush();
  46. LogWriter?.Dispose();
  47. }
  48. ~DiskLogListener()
  49. {
  50. Dispose();
  51. }
  52. }
  53. }