DiskLogListener.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 => { LogWriter?.Flush(); }, null, 2000, 2000);
  33. }
  34. public void LogEvent(object sender, LogEventArgs eventArgs)
  35. {
  36. if (!ConfigWriteUnityLog.Value && 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. private static readonly ConfigWrapper<string> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Wrap(
  53. "Logging.Disk",
  54. "DisplayedLogLevel",
  55. "Only displays the specified log level and above in the console output.",
  56. "Info");
  57. private static readonly ConfigWrapper<bool> ConfigWriteUnityLog = ConfigFile.CoreConfig.Wrap(
  58. "Logging.Disk",
  59. "WriteUnityLog",
  60. "Include unity log messages in log file output.",
  61. false);
  62. private static readonly ConfigWrapper<bool> ConfigAppendLog = ConfigFile.CoreConfig.Wrap(
  63. "Logging.Disk",
  64. "AppendLog",
  65. "Appends to the log file instead of overwriting, on game startup.",
  66. false);
  67. }
  68. }