TraceLogSource.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Diagnostics;
  2. namespace BepInEx.Logging
  3. {
  4. /// <summary>
  5. /// A trace listener that writes to an underlying <see cref="BaseLogger"/> instance.
  6. /// </summary>
  7. /// <inheritdoc cref="TraceListener"/>
  8. public class TraceLogSource : TraceListener
  9. {
  10. public static bool IsListening { get; protected set; } = false;
  11. private static TraceLogSource traceListener;
  12. public static ILogSource CreateSource()
  13. {
  14. if (traceListener == null)
  15. {
  16. traceListener = new TraceLogSource();
  17. Trace.Listeners.Add(traceListener);
  18. IsListening = true;
  19. }
  20. return traceListener.LogSource;
  21. }
  22. protected ManualLogSource LogSource { get; }
  23. /// <param name="logger">The logger instance to write to.</param>
  24. protected TraceLogSource()
  25. {
  26. LogSource = new ManualLogSource("Trace");
  27. }
  28. /// <summary>
  29. /// Writes a message to the underlying <see cref="BaseLogger"/> instance.
  30. /// </summary>
  31. /// <param name="message">The message to write.</param>
  32. public override void Write(string message)
  33. {
  34. LogSource.Log(LogLevel.None, message);
  35. }
  36. /// <summary>
  37. /// Writes a message and a newline to the underlying <see cref="BaseLogger"/> instance.
  38. /// </summary>
  39. /// <param name="message">The message to write.</param>
  40. public override void WriteLine(string message)
  41. {
  42. LogSource.Log(LogLevel.None, $"{message}\r\n");
  43. }
  44. public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
  45. => TraceEvent(eventCache, source, eventType, id, string.Format(format, args));
  46. public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
  47. {
  48. LogLevel level;
  49. switch (eventType)
  50. {
  51. case TraceEventType.Critical:
  52. level = LogLevel.Fatal;
  53. break;
  54. case TraceEventType.Error:
  55. level = LogLevel.Error;
  56. break;
  57. case TraceEventType.Warning:
  58. level = LogLevel.Warning;
  59. break;
  60. case TraceEventType.Information:
  61. level = LogLevel.Info;
  62. break;
  63. case TraceEventType.Verbose:
  64. default:
  65. level = LogLevel.Debug;
  66. break;
  67. }
  68. LogSource.Log(level, $"{source} : {message}");
  69. }
  70. }
  71. }