Browse Source

Add log source for Harmony logs
Rebase of 055eac2

Bepis 3 years ago
parent
commit
9a63f84461

+ 1 - 0
BepInEx.Core/BepInEx.Core.csproj

@@ -75,6 +75,7 @@
     <Compile Include="Configuration\TypeConverter.cs" />
     <Compile Include="Contract\Attributes.cs" />
     <Compile Include="Logging\DiskLogListener.cs" />
+    <Compile Include="Logging\HarmonyLogSource.cs" />
     <Compile Include="Logging\LogEventArgs.cs" />
     <Compile Include="Logging\Logger.cs" />
     <Compile Include="Logging\LogLevel.cs" />

+ 3 - 0
BepInEx.Core/Bootstrap/BaseChainloader.cs

@@ -67,6 +67,9 @@ namespace BepInEx.Bootstrap
 
 			if (!TraceLogSource.IsListening)
 				Logger.Sources.Add(TraceLogSource.CreateSource());
+
+			if (!Logger.Sources.Any(x => x is HarmonyLogSource))
+				Logger.Sources.Add(new HarmonyLogSource());
 		}
 
 		protected virtual IList<PluginInfo> DiscoverPlugins()

+ 46 - 0
BepInEx.Core/Logging/HarmonyLogSource.cs

@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using BepInEx.Configuration;
+using HarmonyLogger = HarmonyLib.Tools.Logger;
+
+namespace BepInEx.Logging
+{
+	public class HarmonyLogSource : ILogSource
+	{
+		private static readonly ConfigEntry<HarmonyLogger.LogChannel> LogChannels = ConfigFile.CoreConfig.Bind(
+			"Harmony.Logger",
+			"LogChannels",
+			HarmonyLogger.LogChannel.Warn | HarmonyLogger.LogChannel.Error,
+			"Specifies which Harmony log channels to listen to.\nNOTE: IL channel dumps the whole patch methods, use only when needed!");
+
+		private static readonly Dictionary<HarmonyLogger.LogChannel, LogLevel> LevelMap = new Dictionary<HarmonyLogger.LogChannel, LogLevel>
+		{
+			[HarmonyLogger.LogChannel.Info] = LogLevel.Info,
+			[HarmonyLogger.LogChannel.Warn] = LogLevel.Warning,
+			[HarmonyLogger.LogChannel.Error] = LogLevel.Error,
+			[HarmonyLogger.LogChannel.IL] = LogLevel.Debug
+		};
+
+		public HarmonyLogSource()
+		{
+			HarmonyLogger.ChannelFilter = LogChannels.Value;
+			HarmonyLogger.MessageReceived += HandleHarmonyMessage;
+		}
+
+		private void HandleHarmonyMessage(object sender, HarmonyLib.Tools.Logger.LogEventArgs e)
+		{
+			if (!LevelMap.TryGetValue(e.LogChannel, out var level))
+				return;
+
+			LogEvent?.Invoke(this, new LogEventArgs(e.Message, level, this));
+		}
+
+		public void Dispose()
+		{
+			HarmonyLogger.MessageReceived -= HandleHarmonyMessage;
+		}
+
+		public string SourceName { get; } = "Harmony";
+		public event EventHandler<LogEventArgs> LogEvent;
+	}
+}

+ 1 - 0
BepInEx.Preloader.Unity/UnityPreloader.cs

@@ -51,6 +51,7 @@ namespace BepInEx.Preloader.Unity
 				}, out var runtimePatchException);
 
 				Logger.Sources.Add(TraceLogSource.CreateSource());
+				Logger.Sources.Add(new HarmonyLogSource());
 
 				PreloaderLog = new PreloaderConsoleListener(ConfigPreloaderCOutLogging.Value);
 				Logger.Listeners.Add(PreloaderLog);