| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- using System;
- using System.Collections.Generic;
- namespace TeamAAS.Logging
- {
- /// <summary>
- /// 内存日志总线:AppLogger / PluginLogger 写文件的同时把结构化条目发布到这里,
- /// 实时日志控件(LogView)订阅 <see cref="Published"/> 联动显示,并可用 <see cref="Snapshot"/> 回填历史。
- /// 发布过程吞掉一切异常,绝不影响业务流程。
- /// </summary>
- public static class LogStream
- {
- /// <summary>环形缓冲容量(新控件加载时可回填的最近条目数)。</summary>
- public const int BufferCapacity = 1000;
- private static readonly object Gate = new object();
- private static readonly Queue<LogEntry> Buffer = new Queue<LogEntry>();
- /// <summary>有新日志条目时触发(可能在任意后台线程触发,订阅方自行切 UI 线程)。</summary>
- public static event Action<LogEntry> Published;
- /// <summary>发布一条日志条目:入环形缓冲并通知订阅者。</summary>
- public static void Publish(LogEntry entry)
- {
- if (entry == null) return;
- lock (Gate)
- {
- Buffer.Enqueue(entry);
- while (Buffer.Count > BufferCapacity)
- Buffer.Dequeue();
- }
- try
- {
- Published?.Invoke(entry);
- }
- catch (Exception ex)
- {
- System.Diagnostics.Debug.WriteLine("[LogStream] publish failed: " + ex.Message);
- }
- }
- /// <summary>返回当前缓冲的快照(最旧→最新),供控件首次加载回填。</summary>
- public static List<LogEntry> Snapshot()
- {
- lock (Gate)
- {
- return new List<LogEntry>(Buffer);
- }
- }
- /// <summary>清空缓冲(不影响已显示在控件里的条目)。</summary>
- public static void Clear()
- {
- lock (Gate)
- {
- Buffer.Clear();
- }
- }
- }
- }
|