Logger.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. namespace BepInEx.Logging
  4. {
  5. /// <summary>
  6. /// A static <see cref="BaseLogger"/> instance.
  7. /// </summary>
  8. public static class Logger
  9. {
  10. public static ICollection<ILogListener> Listeners { get; } = new List<ILogListener>();
  11. public static ICollection<ILogSource> Sources { get; } = new LogSourceCollection();
  12. private static readonly ManualLogSource InternalLogSource = CreateLogSource("BepInEx");
  13. private static bool internalLogsInitialized;
  14. internal static void InitializeInternalLoggers()
  15. {
  16. if (internalLogsInitialized)
  17. return;
  18. Sources.Add(new HarmonyLogSource());
  19. internalLogsInitialized = true;
  20. }
  21. internal static void InternalLogEvent(object sender, LogEventArgs eventArgs)
  22. {
  23. foreach (var listener in Listeners)
  24. {
  25. listener?.LogEvent(sender, eventArgs);
  26. }
  27. }
  28. /// <summary>
  29. /// Logs an entry to the current logger instance.
  30. /// </summary>
  31. /// <param name="level">The level of the entry.</param>
  32. /// <param name="entry">The textual value of the entry.</param>
  33. internal static void Log(LogLevel level, object data)
  34. {
  35. InternalLogSource.Log(level, data);
  36. }
  37. internal static void LogFatal(object data) => Log(LogLevel.Fatal, data);
  38. internal static void LogError(object data) => Log(LogLevel.Error, data);
  39. internal static void LogWarning(object data) => Log(LogLevel.Warning, data);
  40. internal static void LogMessage(object data) => Log(LogLevel.Message, data);
  41. internal static void LogInfo(object data) => Log(LogLevel.Info, data);
  42. internal static void LogDebug(object data) => Log(LogLevel.Debug, data);
  43. public static ManualLogSource CreateLogSource(string sourceName)
  44. {
  45. var source = new ManualLogSource(sourceName);
  46. Sources.Add(source);
  47. return source;
  48. }
  49. private class LogSourceCollection : List<ILogSource>, ICollection<ILogSource>
  50. {
  51. void ICollection<ILogSource>.Add(ILogSource item)
  52. {
  53. if (item == null)
  54. throw new ArgumentNullException(nameof(item), "Log sources cannot be null when added to the source list.");
  55. item.LogEvent += InternalLogEvent;
  56. base.Add(item);
  57. }
  58. void ICollection<ILogSource>.Clear()
  59. {
  60. foreach (var item in base.ToArray())
  61. {
  62. ((ICollection<ILogSource>)this).Remove(item);
  63. }
  64. }
  65. bool ICollection<ILogSource>.Remove(ILogSource item)
  66. {
  67. if (item == null)
  68. return false;
  69. if (!base.Contains(item))
  70. return false;
  71. item.LogEvent -= InternalLogEvent;
  72. base.Remove(item);
  73. return true;
  74. }
  75. }
  76. }
  77. }