PreloaderLogWriter.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Text;
  5. namespace BepInEx.Logger
  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. }
  53. public override void Write(string value)
  54. {
  55. StringBuilder.Append(value);
  56. }
  57. protected override void Dispose(bool disposing)
  58. {
  59. Disable();
  60. StringBuilder.Length = 0;
  61. base.Dispose(disposing);
  62. }
  63. public override string ToString()
  64. {
  65. return StringBuilder.ToString().Trim();
  66. }
  67. }
  68. }