PreloaderLogWriter.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Text;
  5. namespace BepInEx.Logging
  6. {
  7. public class PreloaderLogWriter : BaseLogger
  8. {
  9. public StringBuilder StringBuilder { get; protected set; } = new StringBuilder();
  10. public bool IsRedirectingConsole { get; protected set; }
  11. protected TextWriter stdout;
  12. protected LoggerTraceListener traceListener;
  13. private bool _enabled = false;
  14. public bool Enabled {
  15. get => _enabled;
  16. set
  17. {
  18. if (value)
  19. Enable();
  20. else
  21. Disable();
  22. }
  23. }
  24. public PreloaderLogWriter(bool redirectConsole)
  25. {
  26. IsRedirectingConsole = redirectConsole;
  27. if (IsRedirectingConsole)
  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. Trace.Listeners.Add(traceListener);
  38. _enabled = true;
  39. }
  40. public void Disable()
  41. {
  42. if (!Enabled)
  43. return;
  44. if (IsRedirectingConsole)
  45. Console.SetOut(stdout);
  46. Trace.Listeners.Remove(traceListener);
  47. _enabled = false;
  48. }
  49. public override void Write(char value)
  50. {
  51. StringBuilder.Append(value);
  52. if (IsRedirectingConsole)
  53. stdout.Write(value);
  54. else
  55. Console.Write(value);
  56. }
  57. public override void Write(string value)
  58. {
  59. StringBuilder.Append(value);
  60. if (IsRedirectingConsole)
  61. stdout.Write(value);
  62. else
  63. Console.Write(value);
  64. }
  65. protected override void Dispose(bool disposing)
  66. {
  67. Disable();
  68. StringBuilder.Length = 0;
  69. base.Dispose(disposing);
  70. }
  71. public override string ToString()
  72. {
  73. return StringBuilder.ToString().Trim();
  74. }
  75. }
  76. }