PreloaderLogWriter.cs 2.1 KB

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