PreloaderLogWriter.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using BepInEx.Logging;
  6. namespace BepInEx.Preloader.Core.Logging
  7. {
  8. public class PreloaderConsoleListener : ILogListener
  9. {
  10. public static List<LogEventArgs> LogEvents { get; } = new List<LogEventArgs>();
  11. public static TextWriter StandardOut { get; set; }
  12. protected PreloaderConsoleSource LoggerSource { get; set; }
  13. public PreloaderConsoleListener(bool redirectConsole)
  14. {
  15. StandardOut = Console.Out;
  16. if (redirectConsole)
  17. {
  18. LoggerSource = new PreloaderConsoleSource();
  19. Logger.Sources.Add(LoggerSource);
  20. Console.SetOut(LoggerSource);
  21. }
  22. }
  23. public void LogEvent(object sender, LogEventArgs eventArgs)
  24. {
  25. LogEvents.Add(eventArgs);
  26. ConsoleManager.SetConsoleColor(eventArgs.Level.GetConsoleColor());
  27. ConsoleDirectWrite(eventArgs.ToStringLine());
  28. ConsoleManager.SetConsoleColor(ConsoleColor.Gray);
  29. }
  30. public void ConsoleDirectWrite(string value)
  31. {
  32. StandardOut.Write(value);
  33. }
  34. public void ConsoleDirectWriteLine(string value)
  35. {
  36. StandardOut.WriteLine(value);
  37. }
  38. public void Dispose()
  39. {
  40. if (LoggerSource != null)
  41. {
  42. Console.SetOut(StandardOut);
  43. Logger.Sources.Remove(LoggerSource);
  44. LoggerSource.Dispose();
  45. LoggerSource = null;
  46. }
  47. }
  48. }
  49. public class PreloaderConsoleSource : TextWriter, ILogSource
  50. {
  51. public override Encoding Encoding { get; } = Console.OutputEncoding;
  52. public string SourceName { get; } = "BepInEx Preloader";
  53. public event EventHandler<LogEventArgs> LogEvent;
  54. public override void Write(object value)
  55. => LogEvent?.Invoke(this, new LogEventArgs(value, LogLevel.Info, this));
  56. public override void Write(string value)
  57. => Write((object)value);
  58. public override void WriteLine() { }
  59. public override void WriteLine(object value)
  60. => Write(value);
  61. public override void WriteLine(string value)
  62. => Write(value);
  63. }
  64. }