UnityLogSource.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Reflection;
  3. using UnityEngine;
  4. namespace BepInEx.Logging
  5. {
  6. /// <summary>
  7. /// Logs entries using Unity specific outputs.
  8. /// </summary>
  9. public class UnityLogSource : ILogSource
  10. {
  11. public string SourceName { get; } = "Unity Log";
  12. public event EventHandler<LogEventArgs> LogEvent;
  13. public UnityLogSource()
  14. {
  15. InternalUnityLogMessage += unityLogMessageHandler;
  16. }
  17. private void unityLogMessageHandler(object sender, LogEventArgs eventArgs)
  18. {
  19. var newEventArgs = new LogEventArgs(eventArgs.Data, eventArgs.Level, this);
  20. LogEvent?.Invoke(this, newEventArgs);
  21. }
  22. private bool disposed = false;
  23. public void Dispose()
  24. {
  25. if (!disposed)
  26. {
  27. InternalUnityLogMessage -= unityLogMessageHandler;
  28. disposed = true;
  29. }
  30. }
  31. #region Static Unity handler
  32. private static event EventHandler<LogEventArgs> InternalUnityLogMessage;
  33. static UnityLogSource()
  34. {
  35. var callback = new Application.LogCallback(OnUnityLogMessageReceived);
  36. EventInfo logEvent = typeof(Application).GetEvent("logMessageReceived", BindingFlags.Public | BindingFlags.Static);
  37. if (logEvent != null)
  38. {
  39. logEvent.AddEventHandler(null, callback);
  40. //UnsubscribeAction = () => logEvent.RemoveEventHandler(null, callback);
  41. }
  42. else
  43. {
  44. MethodInfo registerLogCallback = typeof(Application).GetMethod("RegisterLogCallback", BindingFlags.Public | BindingFlags.Static);
  45. registerLogCallback.Invoke(null, new object[] { callback });
  46. //UnsubscribeAction = () => registerLogCallback.Invoke(null, new object[] { null });
  47. }
  48. }
  49. private static void OnUnityLogMessageReceived(string message, string stackTrace, LogType type)
  50. {
  51. LogLevel logLevel;
  52. switch (type)
  53. {
  54. case LogType.Error:
  55. case LogType.Assert:
  56. case LogType.Exception:
  57. logLevel = LogLevel.Error;
  58. break;
  59. case LogType.Warning:
  60. logLevel = LogLevel.Warning;
  61. break;
  62. case LogType.Log:
  63. default:
  64. logLevel = LogLevel.Info;
  65. break;
  66. }
  67. if (type == LogType.Exception)
  68. message += $"\nStack trace:\n{stackTrace}";
  69. InternalUnityLogMessage?.Invoke(null, new LogEventArgs(message, logLevel, null));
  70. }
  71. #endregion
  72. }
  73. }