LogStream.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. namespace TeamAAS.Logging
  4. {
  5. /// <summary>
  6. /// 内存日志总线:AppLogger / PluginLogger 写文件的同时把结构化条目发布到这里,
  7. /// 实时日志控件(LogView)订阅 <see cref="Published"/> 联动显示,并可用 <see cref="Snapshot"/> 回填历史。
  8. /// 发布过程吞掉一切异常,绝不影响业务流程。
  9. /// </summary>
  10. public static class LogStream
  11. {
  12. /// <summary>环形缓冲容量(新控件加载时可回填的最近条目数)。</summary>
  13. public const int BufferCapacity = 1000;
  14. private static readonly object Gate = new object();
  15. private static readonly Queue<LogEntry> Buffer = new Queue<LogEntry>();
  16. /// <summary>有新日志条目时触发(可能在任意后台线程触发,订阅方自行切 UI 线程)。</summary>
  17. public static event Action<LogEntry> Published;
  18. /// <summary>发布一条日志条目:入环形缓冲并通知订阅者。</summary>
  19. public static void Publish(LogEntry entry)
  20. {
  21. if (entry == null) return;
  22. lock (Gate)
  23. {
  24. Buffer.Enqueue(entry);
  25. while (Buffer.Count > BufferCapacity)
  26. Buffer.Dequeue();
  27. }
  28. try
  29. {
  30. Published?.Invoke(entry);
  31. }
  32. catch (Exception ex)
  33. {
  34. System.Diagnostics.Debug.WriteLine("[LogStream] publish failed: " + ex.Message);
  35. }
  36. }
  37. /// <summary>返回当前缓冲的快照(最旧→最新),供控件首次加载回填。</summary>
  38. public static List<LogEntry> Snapshot()
  39. {
  40. lock (Gate)
  41. {
  42. return new List<LogEntry>(Buffer);
  43. }
  44. }
  45. /// <summary>清空缓冲(不影响已显示在控件里的条目)。</summary>
  46. public static void Clear()
  47. {
  48. lock (Gate)
  49. {
  50. Buffer.Clear();
  51. }
  52. }
  53. }
  54. }