소스 검색

Implement a proper logging static class

Bepis 6 년 전
부모
커밋
4e59fdd111

+ 6 - 5
BepInEx/BepInEx.csproj

@@ -67,11 +67,12 @@
     <Compile Include="Bootstrap\Chainloader.cs" />
     <Compile Include="Contract\BaseUnityPlugin.cs" />
     <Compile Include="Deprecated\BepInLogger.cs" />
-    <Compile Include="Logger\BaseLogger.cs" />
-    <Compile Include="Logger\LogLevel.cs" />
-    <Compile Include="Logger\PreloaderLogWriter.cs" />
-    <Compile Include="Logger\LoggerTraceListener.cs" />
-    <Compile Include="Logger\UnityLogWriter.cs" />
+    <Compile Include="Logging\BaseLogger.cs" />
+    <Compile Include="Logging\Logger.cs" />
+    <Compile Include="Logging\LogLevel.cs" />
+    <Compile Include="Logging\PreloaderLogWriter.cs" />
+    <Compile Include="Logging\LoggerTraceListener.cs" />
+    <Compile Include="Logging\UnityLogWriter.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="Bootstrap\TypeLoader.cs" />
   </ItemGroup>

+ 20 - 25
BepInEx/Bootstrap/Chainloader.cs

@@ -4,8 +4,9 @@ using System.Collections.Generic;
 using System.Diagnostics;
 using System.IO;
 using System.Linq;
-using System.Reflection;
+using BepInEx.Logging;
 using UnityEngine;
+using UnityLogWriter = BepInEx.Logging.UnityLogWriter;
 
 namespace BepInEx.Bootstrap
 {
@@ -25,38 +26,32 @@ namespace BepInEx.Bootstrap
 		public static GameObject ManagerObject { get; protected set; } = new GameObject("BepInEx_Manager");
 
 
-		static bool loaded = false;
+		private static bool _loaded = false;
 
 		/// <summary>
 		/// The entry point for BepInEx, called on the very first LoadScene() from UnityEngine.
 		/// </summary>
 		public static void Initialize()
 		{
-			if (loaded)
+			if (_loaded)
 				return;
 
-		    if (!Directory.Exists(Common.Utility.PluginsDirectory))
+		    if (!Directory.Exists(Utility.PluginsDirectory))
 		        Directory.CreateDirectory(Utility.PluginsDirectory);
 
-			if (bool.Parse(Config.GetEntry("console", "false")) || bool.Parse(Config.GetEntry("console-shiftjis", "false")))
-			{
-				try
-				{
-					UnityInjector.ConsoleUtil.ConsoleWindow.Attach();
-
-					if (bool.Parse(Config.GetEntry("console-shiftjis", "false")))
-						UnityInjector.ConsoleUtil.ConsoleEncoding.ConsoleCodePage = 932;
-				}
-				catch
-				{
-					BepInLogger.Log("Failed to allocate console!", true);
-				}
-			}
+            Preloader.AllocateConsole();
 
 			try
 			{
-                BepInLogger.Log(Preloader.PreloaderLog.ToString());
-				BepInLogger.Log("Chainloader started");
+                UnityLogWriter unityLogWriter = new UnityLogWriter();
+
+			    if (Preloader.PreloaderLog != null)
+			        unityLogWriter.WriteToLog(Preloader.PreloaderLog.ToString());
+
+                Logger.SetLogger(unityLogWriter);
+
+                
+				Logger.Log(LogLevel.Message, "Chainloader started");
 
 				UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
 
@@ -76,7 +71,7 @@ namespace BepInEx.Bootstrap
 				    })
 				    .ToList();
 
-				BepInLogger.Log($"{pluginTypes.Count} plugins selected");
+			    Logger.Log(LogLevel.Info, $"{pluginTypes.Count} plugins selected");
 
 				Dictionary<Type, IEnumerable<Type>> dependencyDict = new Dictionary<Type, IEnumerable<Type>>();
 
@@ -92,7 +87,7 @@ namespace BepInEx.Bootstrap
 					{
 						var metadata = MetadataHelper.GetMetadata(t);
 
-						BepInLogger.Log($"Cannot load [{metadata.Name}] due to missing dependencies.");
+					    Logger.Log(LogLevel.Info, $"Cannot load [{metadata.Name}] due to missing dependencies.");
 					}
 				}
 
@@ -107,11 +102,11 @@ namespace BepInEx.Bootstrap
 						var plugin = (BaseUnityPlugin) ManagerObject.AddComponent(t);
 
 						Plugins.Add(plugin);
-						BepInLogger.Log($"Loaded [{metadata.Name} {metadata.Version}]");
+					    Logger.Log(LogLevel.Info, $"Loaded [{metadata.Name} {metadata.Version}]");
 					}
 					catch (Exception ex)
 					{
-						BepInLogger.Log($"Error loading [{t.Name}] : {ex.Message}");
+					    Logger.Log(LogLevel.Info, $"Error loading [{t.Name}] : {ex.Message}");
 					}
 				}
 			}
@@ -123,7 +118,7 @@ namespace BepInEx.Bootstrap
 				Console.WriteLine(ex.ToString());
 			}
 
-			loaded = true;
+			_loaded = true;
 		}
 	}
 }

+ 34 - 13
BepInEx/Bootstrap/Preloader.cs

@@ -5,7 +5,7 @@ using System.IO;
 using System.Linq;
 using System.Reflection;
 using BepInEx.Common;
-using BepInEx.Logger;
+using BepInEx.Logging;
 using Mono.Cecil;
 using Mono.Cecil.Cil;
 using MethodAttributes = Mono.Cecil.MethodAttributes;
@@ -67,19 +67,44 @@ namespace BepInEx.Bootstrap
             }
         }
 
+        internal static void AllocateConsole()
+        {
+            bool console = TryGetConfigBool("console", "false");
+            bool shiftjis = TryGetConfigBool("console-shiftjis", "false");
+
+            if (console)
+            {
+                try
+                {
+                    UnityInjector.ConsoleUtil.ConsoleWindow.Attach();
+
+                    if (shiftjis)
+                        UnityInjector.ConsoleUtil.ConsoleEncoding.ConsoleCodePage = 932;
+                }
+                catch (Exception ex)
+                {
+                    Logger.Log(LogLevel.Error, "Failed to allocate console!");
+                    Logger.Log(LogLevel.Error, ex);
+                }
+            }
+        }
+
         public static void Main(string[] args)
         {
             try
             {
                 AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
                 ExecutablePath = args[0];
-
+                
+                AllocateConsole();
 
                 PreloaderLog = new PreloaderLogWriter(TryGetConfigBool("preloader-logconsole", "false"));
                 PreloaderLog.Enabled = true;
 
-                PreloaderLog.WriteLine($"BepInEx {Assembly.GetExecutingAssembly().GetName().Version}");
-                PreloaderLog.Log(LogLevel.Message, "Preloader started");
+                Logger.SetLogger(PreloaderLog);
+
+                Logger.CurrentLogger.WriteLine($"BepInEx {Assembly.GetExecutingAssembly().GetName().Version}");
+                Logger.Log(LogLevel.Message, "Preloader started");
 
 
 
@@ -104,8 +129,8 @@ namespace BepInEx.Bootstrap
             }
             catch (Exception ex)
             {
-                PreloaderLog.Log(LogLevel.Fatal, "Could not run preloader!");
-                PreloaderLog.Log(LogLevel.Fatal, ex);
+                Logger.Log(LogLevel.Fatal, "Could not run preloader!");
+                Logger.Log(LogLevel.Fatal, ex);
 
                 PreloaderLog.Disable();
 
@@ -122,10 +147,6 @@ namespace BepInEx.Bootstrap
                     PreloaderLog.Dispose();
                 }
             }
-            finally
-            {
-                PreloaderLog.Enabled = false;
-            }
         }
 
         internal static IDictionary<string, IList<AssemblyPatcherDelegate>> GetPatcherMethods(Assembly assembly)
@@ -176,12 +197,12 @@ namespace BepInEx.Bootstrap
                 }
                 catch (Exception ex)
                 {
-                    PreloaderLog.Log(LogLevel.Warning, $"Could not load patcher methods from {assembly.GetName().Name}");
-                    PreloaderLog.Log(LogLevel.Warning, $"{ex}");
+                    Logger.Log(LogLevel.Warning, $"Could not load patcher methods from {assembly.GetName().Name}");
+                    Logger.Log(LogLevel.Warning, $"{ex}");
                 }
             }
 
-            PreloaderLog.Log(LogLevel.Info, $"Loaded {patcherMethods.SelectMany(x => x.Value).Distinct().Count()} patcher methods from {assembly.GetName().Name}");
+            Logger.Log(LogLevel.Info, $"Loaded {patcherMethods.SelectMany(x => x.Value).Distinct().Count()} patcher methods from {assembly.GetName().Name}");
 
             return patcherMethods;
         }

+ 2 - 1
BepInEx/Bootstrap/TypeLoader.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.IO;
 using System.Reflection;
+using BepInEx.Logging;
 
 namespace BepInEx.Bootstrap
 {
@@ -34,7 +35,7 @@ namespace BepInEx.Bootstrap
                 catch (BadImageFormatException) { } //unmanaged DLL
                 catch (ReflectionTypeLoadException)
                 {
-                    BepInLogger.Log($"ERROR! Could not load \"{Path.GetFileName(dll)}\" as a plugin!");
+                    Logger.Log(LogLevel.Error, $"Could not load \"{Path.GetFileName(dll)}\" as a plugin!");
                 }
             }
 

+ 3 - 2
BepInEx/ConfigWrapper.cs

@@ -1,5 +1,6 @@
 using System;
 using System.ComponentModel;
+using BepInEx.Logging;
 
 namespace BepInEx
 {
@@ -116,7 +117,7 @@ namespace BepInEx
             }
             catch (Exception ex)
             {
-                BepInLogger.Log("ConfigWrapper Get Converter Exception: " + ex.Message);
+                Logger.Log(LogLevel.Error, "ConfigWrapper Get Converter Exception: " + ex.Message);
                 return _default;
             }
         }
@@ -130,7 +131,7 @@ namespace BepInEx
             }
             catch (Exception ex)
             {
-                BepInLogger.Log("ConfigWrapper Set Converter Exception: " + ex.Message);
+                Logger.Log(LogLevel.Error, "ConfigWrapper Set Converter Exception: " + ex.Message);
             }
         }
 

+ 0 - 1
BepInEx/Deprecated/BepInLogger.cs

@@ -1,5 +1,4 @@
 using System;
-using System.Runtime.CompilerServices;
 using BepInEx.ConsoleUtil;
 
 namespace BepInEx

+ 1 - 1
BepInEx/Logger/BaseLogger.cs

@@ -1,7 +1,7 @@
 using System.IO;
 using System.Text;
 
-namespace BepInEx.Logger
+namespace BepInEx.Logging
 {
     public abstract class BaseLogger : TextWriter
     {

+ 1 - 1
BepInEx/Logger/LogLevel.cs

@@ -1,6 +1,6 @@
 using System;
 
-namespace BepInEx.Logger
+namespace BepInEx.Logging
 {
     [Flags]
     public enum LogLevel

+ 21 - 0
BepInEx/Logging/Logger.cs

@@ -0,0 +1,21 @@
+using BepInEx.Logging;
+
+namespace BepInEx
+{
+    public static class Logger
+    {
+        public static BaseLogger CurrentLogger { get; set; }
+
+        public static void Log(LogLevel level, object entry)
+        {
+            CurrentLogger?.Log(level, entry);
+        }
+
+        public static void SetLogger(BaseLogger logger)
+        {
+            CurrentLogger?.Dispose();
+
+            CurrentLogger = logger;
+        }
+    }
+}

+ 1 - 1
BepInEx/Logger/LoggerTraceListener.cs

@@ -4,7 +4,7 @@ using System.Linq;
 using System.Reflection;
 using Harmony;
 
-namespace BepInEx.Logger
+namespace BepInEx.Logging
 {
     public class LoggerTraceListener : TraceListener
     {

+ 11 - 1
BepInEx/Logger/PreloaderLogWriter.cs

@@ -3,7 +3,7 @@ using System.Diagnostics;
 using System.IO;
 using System.Text;
 
-namespace BepInEx.Logger
+namespace BepInEx.Logging
 {
     public class PreloaderLogWriter : BaseLogger
     {
@@ -65,11 +65,21 @@ namespace BepInEx.Logger
         public override void Write(char value)
         {
             StringBuilder.Append(value);
+
+            if (IsRedirectingConsole)
+                stdout.Write(value);
+            else
+                Console.Write(value);
         }
 
         public override void Write(string value)
         {
             StringBuilder.Append(value);
+
+            if (IsRedirectingConsole)
+                stdout.Write(value);
+            else
+                Console.Write(value);
         }
 
         protected override void Dispose(bool disposing)

+ 11 - 9
BepInEx/Logger/UnityLogWriter.cs

@@ -1,22 +1,24 @@
 using System;
-using System.Collections.Generic;
-using System.Linq;
 using System.Runtime.CompilerServices;
-using System.Text;
 
-namespace BepInEx.Logger
+namespace BepInEx.Logging
 {
     public class UnityLogWriter : BaseLogger
     {
-        public void WriteToUnity(string value)
+        public void WriteToLog(string value)
         {
-            Console.Write(value);
             UnityEngine.UnityLogWriter.WriteStringToUnityLog(value);
         }
 
-        public override void WriteLine(string value) => WriteToUnity($"{value}\r\n");
-        public override void Write(char value) => WriteToUnity(value.ToString());
-        public override void Write(string value) => WriteToUnity(value);
+        protected void InternalWrite(string value)
+        {
+            Console.Write(value);
+            WriteToLog(value);
+        }
+
+        public override void WriteLine(string value) => InternalWrite($"{value}\r\n");
+        public override void Write(char value) => InternalWrite(value.ToString());
+        public override void Write(string value) => InternalWrite(value);
     }
 }