PreloaderLogWriter.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Text;
  5. using BepInEx.ConsoleUtil;
  6. namespace BepInEx.Logging
  7. {
  8. public class PreloaderLogWriter : BaseLogger
  9. {
  10. public StringBuilder StringBuilder { get; protected set; } = new StringBuilder();
  11. public bool IsRedirectingConsole { get; protected set; }
  12. protected TextWriter stdout;
  13. protected LoggerTraceListener traceListener;
  14. private bool _enabled = false;
  15. public bool Enabled {
  16. get => _enabled;
  17. set
  18. {
  19. if (value)
  20. Enable();
  21. else
  22. Disable();
  23. }
  24. }
  25. public PreloaderLogWriter(bool redirectConsole)
  26. {
  27. IsRedirectingConsole = redirectConsole;
  28. stdout = Console.Out;
  29. traceListener = new LoggerTraceListener(this);
  30. }
  31. public void Enable()
  32. {
  33. if (_enabled)
  34. return;
  35. if (IsRedirectingConsole)
  36. Console.SetOut(this);
  37. else
  38. Console.SetOut(TextWriter.Null);
  39. Trace.Listeners.Add(traceListener);
  40. _enabled = true;
  41. }
  42. public void Disable()
  43. {
  44. if (!_enabled)
  45. return;
  46. Console.SetOut(stdout);
  47. Trace.Listeners.Remove(traceListener);
  48. _enabled = false;
  49. }
  50. public override void Log(LogLevel level, object entry)
  51. {
  52. Kon.ForegroundColor = level.GetConsoleColor();
  53. base.Log(level, entry);
  54. Kon.ForegroundColor = ConsoleColor.Gray;
  55. }
  56. public override void Write(char value)
  57. {
  58. StringBuilder.Append(value);
  59. stdout.Write(value);
  60. }
  61. public override void Write(string value)
  62. {
  63. StringBuilder.Append(value);
  64. stdout.Write(value);
  65. }
  66. protected override void Dispose(bool disposing)
  67. {
  68. Disable();
  69. StringBuilder.Length = 0;
  70. traceListener?.Dispose();
  71. traceListener = null;
  72. }
  73. public override string ToString()
  74. {
  75. return StringBuilder.ToString().Trim();
  76. }
  77. }
  78. }