UnityLogListener.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using BepInEx.Logging;
  2. using System;
  3. using System.Reflection;
  4. using System.Runtime.CompilerServices;
  5. using System.Text;
  6. using BepInEx.Configuration;
  7. namespace BepInEx.Unity.Logging
  8. {
  9. /// <summary>
  10. /// Logs entries using Unity specific outputs.
  11. /// </summary>
  12. public class UnityLogListener : ILogListener
  13. {
  14. internal static readonly Action<string> WriteStringToUnityLog;
  15. static UnityLogListener()
  16. {
  17. foreach (MethodInfo methodInfo in typeof(UnityEngine.UnityLogWriter).GetMethods(BindingFlags.Static | BindingFlags.Public))
  18. {
  19. try
  20. {
  21. methodInfo.Invoke(null, new object[] { "" });
  22. }
  23. catch
  24. {
  25. continue;
  26. }
  27. WriteStringToUnityLog = (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), methodInfo);
  28. break;
  29. }
  30. if (WriteStringToUnityLog == null)
  31. Logger.LogError("Unable to start Unity log writer");
  32. }
  33. /// <inheritdoc />
  34. public void LogEvent(object sender, LogEventArgs eventArgs)
  35. {
  36. if (eventArgs.Source is UnityLogSource)
  37. return;
  38. // Special case: don't write console twice since Unity can already do that
  39. if (LogConsoleToUnity.Value || eventArgs.Source.SourceName != "Console")
  40. WriteStringToUnityLog?.Invoke(eventArgs.ToStringLine());
  41. }
  42. /// <inheritdoc />
  43. public void Dispose() { }
  44. private readonly ConfigEntry<bool> LogConsoleToUnity = ConfigFile.CoreConfig.Bind("Logging",
  45. "LogConsoleToUnityLog", false,
  46. new StringBuilder()
  47. .AppendLine("If enabled, writes Standard Output messages to Unity log")
  48. .AppendLine("NOTE: By default, Unity does so automatically. Only use this option if no console messages are visible in Unity log").ToString());
  49. }
  50. }
  51. namespace UnityEngine
  52. {
  53. internal sealed class UnityLogWriter
  54. {
  55. [MethodImpl(MethodImplOptions.InternalCall)]
  56. public static extern void WriteStringToUnityLogImpl(string s);
  57. [MethodImpl(MethodImplOptions.InternalCall)]
  58. public static extern void WriteStringToUnityLog(string s);
  59. }
  60. }