UnityLogListener.cs 1.3 KB

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