BaseLogger.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.IO;
  2. using System.Text;
  3. namespace BepInEx.Logging
  4. {
  5. /// <summary>
  6. /// The base implementation of a logging class.
  7. /// </summary>
  8. public abstract class BaseLogger : TextWriter
  9. {
  10. /// <summary>
  11. /// The encoding that the underlying text writer should use. Defaults to UTF-8 BOM.
  12. /// </summary>
  13. public override Encoding Encoding { get; } = new UTF8Encoding(true);
  14. /// <summary>
  15. /// The handler for a entry logged event.
  16. /// </summary>
  17. /// <param name="entry">The text element of the log itself.</param>
  18. /// <param name="show">Whether or not it should be dislpayed to the user.</param>
  19. public delegate void EntryLoggedEventHandler(LogLevel level, object entry);
  20. /// <summary>
  21. /// The listener event for an entry being logged.
  22. /// </summary>
  23. public event EntryLoggedEventHandler EntryLogged;
  24. /// <summary>
  25. /// A filter which is used to specify which log levels are not ignored by the logger.
  26. /// </summary>
  27. public LogLevel DisplayedLevels { get; set; } = LogLevel.All;
  28. private object logLockObj = new object();
  29. /// <summary>
  30. /// Logs an entry to the Logger instance.
  31. /// </summary>
  32. /// <param name="level">The level of the entry.</param>
  33. /// <param name="entry">The textual value of the entry.</param>
  34. public virtual void Log(LogLevel level, object entry)
  35. {
  36. if ((DisplayedLevels & level) != LogLevel.None)
  37. {
  38. lock (logLockObj)
  39. {
  40. EntryLogged?.Invoke(level, entry);
  41. WriteLine($"[{level.GetHighestLevel()}] {entry}");
  42. }
  43. }
  44. }
  45. /// <summary>
  46. /// Logs an entry to the Logger instance, with a <see cref="LogLevel"/> of Message.
  47. /// </summary>
  48. /// <param name="entry">The text value of this log entry.</param>
  49. public virtual void Log(object entry)
  50. {
  51. Log(LogLevel.Message, entry);
  52. }
  53. }
  54. }