DiskLogListener.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.IO;
  2. using System.Text;
  3. using System.Threading;
  4. using BepInEx.Configuration;
  5. namespace BepInEx.Logging
  6. {
  7. /// <summary>
  8. /// Logs entries using Unity specific outputs.
  9. /// </summary>
  10. public class DiskLogListener : ILogListener
  11. {
  12. protected TextWriter LogWriter { get; set; }
  13. protected Timer FlushTimer { get; set; }
  14. public DiskLogListener()
  15. {
  16. int counter = 1;
  17. string localPath = "LogOutput.log";
  18. FileStream fileStream;
  19. while (!Utility.TryOpenFileStream(Path.Combine(Paths.BepInExRootPath, localPath), ConfigAppendLog.Value ? FileMode.Append : FileMode.Create, out fileStream, share: FileShare.Read))
  20. {
  21. if (counter == 5)
  22. {
  23. Logger.LogError("Couldn't open a log file for writing. Skipping log file creation");
  24. return;
  25. }
  26. Logger.LogWarning($"Couldn't open log file '{localPath}' for writing, trying another...");
  27. localPath = $"LogOutput.log.{counter++}";
  28. }
  29. LogWriter = TextWriter.Synchronized(new StreamWriter(fileStream, Encoding.UTF8));
  30. FlushTimer = new Timer(o => { LogWriter?.Flush(); }, null, 2000, 2000);
  31. }
  32. public void LogEvent(object sender, LogEventArgs eventArgs)
  33. {
  34. if (!ConfigWriteUnityLog.Value && eventArgs.Source is UnityLogSource)
  35. return;
  36. if (eventArgs.Level.GetHighestLevel() > ConfigConsoleDisplayedLevel.Value)
  37. return;
  38. LogWriter.WriteLine($"[{eventArgs.Level,-7}:{((ILogSource)sender).SourceName,10}] {eventArgs.Data}");
  39. }
  40. public void Dispose()
  41. {
  42. FlushTimer?.Dispose();
  43. LogWriter?.Flush();
  44. LogWriter?.Dispose();
  45. }
  46. ~DiskLogListener()
  47. {
  48. Dispose();
  49. }
  50. private static readonly ConfigWrapper<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Wrap(
  51. "Logging.Disk", "DisplayedLogLevel",
  52. LogLevel.Info,
  53. new ConfigDescription("Only displays the specified log level and above in the console output."));
  54. private static readonly ConfigWrapper<bool> ConfigWriteUnityLog = ConfigFile.CoreConfig.Wrap(
  55. "Logging.Disk", "WriteUnityLog",
  56. false,
  57. new ConfigDescription("Include unity log messages in log file output."));
  58. private static readonly ConfigWrapper<bool> ConfigAppendLog = ConfigFile.CoreConfig.Wrap(
  59. "Logging.Disk", "AppendLog",
  60. false,
  61. new ConfigDescription("Appends to the log file instead of overwriting, on game startup."));
  62. }
  63. }