Logger.cs 2.3 KB

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