ConsoleSetOutFix.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using BepInEx.Logging;
  5. using HarmonyLib;
  6. namespace BepInEx.Preloader.RuntimeFixes
  7. {
  8. public static class ConsoleSetOutFix
  9. {
  10. private static LoggedTextWriter loggedTextWriter;
  11. internal static ManualLogSource ConsoleLogSource = Logger.CreateLogSource("Console");
  12. public static void Apply()
  13. {
  14. loggedTextWriter = new LoggedTextWriter { Parent = Console.Out };
  15. Console.SetOut(loggedTextWriter);
  16. HarmonyLib.Harmony.CreateAndPatchAll(typeof(ConsoleSetOutFix));
  17. }
  18. [HarmonyPatch(typeof(Console), nameof(Console.SetOut))]
  19. [HarmonyPrefix]
  20. private static bool OnSetOut(TextWriter newOut)
  21. {
  22. loggedTextWriter.Parent = newOut;
  23. return false;
  24. }
  25. }
  26. internal class LoggedTextWriter : TextWriter
  27. {
  28. public override Encoding Encoding { get; } = Encoding.UTF8;
  29. public TextWriter Parent { get; set; }
  30. public override void Flush() => Parent.Flush();
  31. public override void Write(string value)
  32. {
  33. ConsoleSetOutFix.ConsoleLogSource.LogInfo(value);
  34. Parent.Write(value);
  35. }
  36. public override void WriteLine(string value)
  37. {
  38. ConsoleSetOutFix.ConsoleLogSource.LogInfo(value);
  39. Parent.WriteLine(value);
  40. }
  41. }
  42. }