Logger.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. internal static void InternalLogEvent(object sender, LogEventArgs eventArgs)
  14. {
  15. foreach (var listener in Listeners)
  16. {
  17. listener?.LogEvent(sender, eventArgs);
  18. }
  19. }
  20. /// <summary>
  21. /// Logs an entry to the current logger instance.
  22. /// </summary>
  23. /// <param name="level">The level of the entry.</param>
  24. /// <param name="entry">The textual value of the entry.</param>
  25. internal static void Log(LogLevel level, object data)
  26. {
  27. InternalLogSource.Log(level, data);
  28. }
  29. internal static void LogFatal(object data) => Log(LogLevel.Fatal, data);
  30. internal static void LogError(object data) => Log(LogLevel.Error, data);
  31. internal static void LogWarning(object data) => Log(LogLevel.Warning, data);
  32. internal static void LogMessage(object data) => Log(LogLevel.Message, data);
  33. internal static void LogInfo(object data) => Log(LogLevel.Info, data);
  34. internal static void LogDebug(object data) => Log(LogLevel.Debug, data);
  35. public static ManualLogSource CreateLogSource(string sourceName)
  36. {
  37. var source = new ManualLogSource(sourceName);
  38. Sources.Add(source);
  39. return source;
  40. }
  41. private class LogSourceCollection : List<ILogSource>, ICollection<ILogSource>
  42. {
  43. void ICollection<ILogSource>.Add(ILogSource item)
  44. {
  45. if (item == null)
  46. throw new ArgumentNullException(nameof(item), "Log sources cannot be null when added to the source list.");
  47. item.LogEvent += InternalLogEvent;
  48. base.Add(item);
  49. }
  50. void ICollection<ILogSource>.Clear()
  51. {
  52. foreach (var item in base.ToArray())
  53. {
  54. ((ICollection<ILogSource>)this).Remove(item);
  55. }
  56. }
  57. bool ICollection<ILogSource>.Remove(ILogSource item)
  58. {
  59. if (item == null)
  60. return false;
  61. if (!base.Contains(item))
  62. return false;
  63. item.LogEvent -= InternalLogEvent;
  64. base.Remove(item);
  65. return true;
  66. }
  67. }
  68. }
  69. }