PreloaderTextWriter.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Text;
  5. namespace BepInEx.Logger
  6. {
  7. public class PreloaderTextWriter : BaseLogger
  8. {
  9. public override Encoding Encoding { get; } = new UTF8Encoding(true);
  10. public StringBuilder StringBuilder = new StringBuilder();
  11. protected TextWriter stdout;
  12. protected TextWriterTraceListener 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 PreloaderTextWriter()
  25. {
  26. stdout = Console.Out;
  27. traceListener = new TextWriterTraceListener(this, "Preloader");
  28. }
  29. public void Enable()
  30. {
  31. if (Enabled)
  32. return;
  33. Console.SetOut(this);
  34. Trace.Listeners.Add(traceListener);
  35. _enabled = true;
  36. }
  37. public void Disable()
  38. {
  39. if (!Enabled)
  40. return;
  41. Console.SetOut(stdout);
  42. Trace.Listeners.Remove(traceListener);
  43. _enabled = false;
  44. }
  45. public override void Write(char value)
  46. {
  47. StringBuilder.Append(value);
  48. }
  49. public override void Write(string value)
  50. {
  51. StringBuilder.Append(value);
  52. }
  53. public override void Close()
  54. {
  55. Disable();
  56. StringBuilder.Length = 0;
  57. }
  58. public override string ToString()
  59. {
  60. return StringBuilder.ToString().Trim();
  61. }
  62. }
  63. }