HarmonyLogSource.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. using BepInEx.Configuration;
  4. using HarmonyLogger = HarmonyLib.Tools.Logger;
  5. namespace BepInEx.Logging
  6. {
  7. public class HarmonyLogSource : ILogSource
  8. {
  9. private static readonly ConfigEntry<HarmonyLogger.LogChannel> LogChannels = ConfigFile.CoreConfig.Bind(
  10. "Harmony.Logger",
  11. "LogChannels",
  12. HarmonyLogger.LogChannel.Warn | HarmonyLogger.LogChannel.Error,
  13. "Specifies which Harmony log channels to listen to.\nNOTE: IL channel dumps the whole patch methods, use only when needed!");
  14. private static readonly Dictionary<HarmonyLogger.LogChannel, LogLevel> LevelMap = new Dictionary<HarmonyLogger.LogChannel, LogLevel>
  15. {
  16. [HarmonyLogger.LogChannel.Info] = LogLevel.Info,
  17. [HarmonyLogger.LogChannel.Warn] = LogLevel.Warning,
  18. [HarmonyLogger.LogChannel.Error] = LogLevel.Error,
  19. [HarmonyLogger.LogChannel.IL] = LogLevel.Debug
  20. };
  21. public HarmonyLogSource()
  22. {
  23. HarmonyLogger.ChannelFilter = LogChannels.Value;
  24. HarmonyLogger.MessageReceived += HandleHarmonyMessage;
  25. }
  26. private void HandleHarmonyMessage(object sender, HarmonyLib.Tools.Logger.LogEventArgs e)
  27. {
  28. if (!LevelMap.TryGetValue(e.LogChannel, out var level))
  29. return;
  30. LogEvent?.Invoke(this, new LogEventArgs(e.Message, level, this));
  31. }
  32. public void Dispose()
  33. {
  34. HarmonyLogger.MessageReceived -= HandleHarmonyMessage;
  35. }
  36. public string SourceName { get; } = "HarmonyX";
  37. public event EventHandler<LogEventArgs> LogEvent;
  38. }
  39. }