DiskLogListener.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Threading;
  5. using BepInEx.Configuration;
  6. namespace BepInEx.Logging
  7. {
  8. /// <summary>
  9. /// Logs entries using Unity specific outputs.
  10. /// </summary>
  11. public class DiskLogListener : ILogListener
  12. {
  13. protected LogLevel DisplayedLogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), ConfigConsoleDisplayedLevel.Value, true);
  14. protected TextWriter LogWriter { get; set; }
  15. protected Timer FlushTimer { get; set; }
  16. public DiskLogListener()
  17. {
  18. int counter = 1;
  19. string localPath = "LogOutput.log";
  20. FileStream fileStream;
  21. while (!Utility.TryOpenFileStream(Path.Combine(Paths.BepInExRootPath, localPath), ConfigAppendLog.Value ? 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 =>
  33. {
  34. LogWriter?.Flush();
  35. }, null, 2000, 2000);
  36. }
  37. public void LogEvent(object sender, LogEventArgs eventArgs)
  38. {
  39. if (!ConfigWriteUnityLog.Value && eventArgs.Source is UnityLogSource)
  40. return;
  41. if (eventArgs.Level.GetHighestLevel() > DisplayedLogLevel)
  42. return;
  43. LogWriter.WriteLine($"[{eventArgs.Level,-7}:{((ILogSource)sender).SourceName,10}] {eventArgs.Data}");
  44. }
  45. public void Dispose()
  46. {
  47. FlushTimer?.Dispose();
  48. LogWriter?.Flush();
  49. LogWriter?.Dispose();
  50. }
  51. ~DiskLogListener()
  52. {
  53. Dispose();
  54. }
  55. private static readonly ConfigWrapper<string> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Wrap(
  56. "Logging.Disk",
  57. "DisplayedLogLevel",
  58. "Only displays the specified log level and above in the console output.",
  59. "Info");
  60. private static readonly ConfigWrapper<bool> ConfigWriteUnityLog = ConfigFile.CoreConfig.Wrap(
  61. "Logging.Disk",
  62. "WriteUnityLog",
  63. "Include unity log messages in log file output.",
  64. false);
  65. private static readonly ConfigWrapper<bool> ConfigAppendLog = ConfigFile.CoreConfig.Wrap(
  66. "Logging.Disk",
  67. "AppendLog",
  68. "Appends to the log file instead of overwriting, on game startup.",
  69. false);
  70. }
  71. }