PreloaderLogWriter.cs 2.1 KB

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