Logger.cs 2.2 KB

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