DiskLogListener.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 = TextWriter.Synchronized(new StreamWriter(Path.Combine(Paths.BepInExRootPath, "LogOutput.log"), ConfigAppendLog.Value, Encoding.UTF8));
  15. protected Timer FlushTimer;
  16. public DiskLogListener()
  17. {
  18. FlushTimer = new Timer(o =>
  19. {
  20. LogWriter?.Flush();
  21. }, null, 2000, 2000);
  22. }
  23. public void LogEvent(object sender, LogEventArgs eventArgs)
  24. {
  25. if (!ConfigWriteUnityLog.Value && eventArgs.Source is UnityLogSource)
  26. return;
  27. if (eventArgs.Level.GetHighestLevel() > DisplayedLogLevel)
  28. return;
  29. LogWriter.WriteLine($"[{eventArgs.Level,-7}:{((ILogSource)sender).SourceName,10}] {eventArgs.Data}");
  30. }
  31. public void Dispose()
  32. {
  33. FlushTimer.Dispose();
  34. LogWriter.Flush();
  35. LogWriter.Dispose();
  36. }
  37. ~DiskLogListener()
  38. {
  39. Dispose();
  40. }
  41. private static readonly ConfigWrapper<string> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Wrap(
  42. "Logging.Disk",
  43. "DisplayedLogLevel",
  44. "Only displays the specified log level and above in the console output.",
  45. "Info");
  46. private static readonly ConfigWrapper<bool> ConfigWriteUnityLog = ConfigFile.CoreConfig.Wrap(
  47. "Logging.Disk",
  48. "WriteUnityLog",
  49. "Include unity log messages in log file output.",
  50. false);
  51. private static readonly ConfigWrapper<bool> ConfigAppendLog = ConfigFile.CoreConfig.Wrap(
  52. "Logging.Disk",
  53. "AppendLog",
  54. "Appends to the log file instead of overwriting, on game startup.",
  55. false);
  56. }
  57. }