PreloaderLogWriter.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. stdout = Console.Out;
  28. traceListener = new LoggerTraceListener(this);
  29. }
  30. public void Enable()
  31. {
  32. if (_enabled)
  33. return;
  34. if (IsRedirectingConsole)
  35. Console.SetOut(this);
  36. else
  37. Console.SetOut(TextWriter.Null);
  38. Trace.Listeners.Add(traceListener);
  39. _enabled = true;
  40. }
  41. public void Disable()
  42. {
  43. if (!_enabled)
  44. return;
  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. stdout.Write(value);
  53. }
  54. public override void Write(string value)
  55. {
  56. StringBuilder.Append(value);
  57. stdout.Write(value);
  58. }
  59. protected override void Dispose(bool disposing)
  60. {
  61. Disable();
  62. StringBuilder.Length = 0;
  63. traceListener?.Dispose();
  64. traceListener = null;
  65. }
  66. public override string ToString()
  67. {
  68. return StringBuilder.ToString().Trim();
  69. }
  70. }
  71. }