UnityLogListener.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using BepInEx.Logging;
  2. using System;
  3. using System.Reflection;
  4. using System.Runtime.CompilerServices;
  5. namespace BepInEx.Unity.Logging
  6. {
  7. /// <summary>
  8. /// Logs entries using Unity specific outputs.
  9. /// </summary>
  10. public class UnityLogListener : ILogListener
  11. {
  12. internal static readonly Action<string> WriteStringToUnityLog;
  13. static UnityLogListener()
  14. {
  15. foreach (MethodInfo methodInfo in typeof(UnityEngine.UnityLogWriter).GetMethods(BindingFlags.Static | BindingFlags.Public))
  16. {
  17. try
  18. {
  19. methodInfo.Invoke(null, new object[] { "" });
  20. }
  21. catch
  22. {
  23. continue;
  24. }
  25. WriteStringToUnityLog = (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), methodInfo);
  26. break;
  27. }
  28. if (WriteStringToUnityLog == null)
  29. Logger.LogError("Unable to start Unity log writer");
  30. }
  31. public void LogEvent(object sender, LogEventArgs eventArgs)
  32. {
  33. if (sender is UnityLogSource)
  34. return;
  35. string log = $"[{eventArgs.Level}:{((ILogSource)sender).SourceName}] {eventArgs.Data}\r\n";
  36. WriteStringToUnityLog?.Invoke(log);
  37. }
  38. public void Dispose() { }
  39. }
  40. }
  41. namespace UnityEngine
  42. {
  43. internal sealed class UnityLogWriter
  44. {
  45. [MethodImpl(MethodImplOptions.InternalCall)]
  46. public static extern void WriteStringToUnityLogImpl(string s);
  47. [MethodImpl(MethodImplOptions.InternalCall)]
  48. public static extern void WriteStringToUnityLog(string s);
  49. }
  50. }