loadViewerLogs function

Future<List<LogEntry>> loadViewerLogs({
  1. DateTime? windowStart,
  2. LogLevel? minLevel,
})
  • @Author: chuxiong
  • @Created at: 2026/10/27
  • @Email:
  • @Company: 嘉联支付
  • description 日志查看器数据装配层 日志查看器数据装配:从 logCollector 拉取全量日志并整理为查看器面板 可直接消费的条目列表。

LogCollector.getAllLogs 返回内存与文件两路的合并结果——同一条日志既在 内存队列中又在落盘文件中,天然带重复。本函数的处理管线:

  1. 稳定键去重(timestamp+level+tag+message+source,保留首现);
  2. 时间窗过滤(windowStart,timestamp >= windowStart 含边界);
  3. 级别阈值过滤(minLevel,level.index >= minLevel.index 含边界);
  4. 按 timestamp 升序返回——面板显示时自行倒序(最新在前)。

Implementation

/// 日志查看器数据装配:从 [logCollector] 拉取全量日志并整理为查看器面板
/// 可直接消费的条目列表。
///
/// [LogCollector.getAllLogs] 返回内存与文件两路的合并结果——同一条日志既在
/// 内存队列中又在落盘文件中,天然带重复。本函数的处理管线:
///
/// 1. 稳定键去重(timestamp+level+tag+message+source,保留首现);
/// 2. 时间窗过滤([windowStart],`timestamp >= windowStart` 含边界);
/// 3. 级别阈值过滤([minLevel],`level.index >= minLevel.index` 含边界);
/// 4. 按 timestamp **升序**返回——面板显示时自行倒序(最新在前)。
Future<List<LogEntry>> loadViewerLogs({
  DateTime? windowStart,
  LogLevel? minLevel,
}) async {
  final all = await logCollector.getAllLogs();

  // 稳定键去重:Set 字面量即 LinkedHashSet(按插入序),add 命中重复返回
  // false——保留首现条目。getAllLogs 先内存后文件,因此内存中的原对象
  // (保留 suppressConsole 等未持久化字段)胜出,文件读回的 JSON 副本被丢弃。
  final seenKeys = <String>{};
  final deduped = <LogEntry>[];
  for (final entry in all) {
    if (seenKeys.add(_stableKey(entry))) {
      deduped.add(entry);
    }
  }

  // 两级过滤(均为含边界 >=):时间窗与级别阈值。
  return deduped
      .where(
        (entry) =>
            (windowStart == null || !entry.timestamp.isBefore(windowStart)) &&
            (minLevel == null || entry.level.index >= minLevel.index),
      )
      .toList()
    // 升序返回;面板显示时自行倒序(最新在前)。
    ..sort((a, b) => a.timestamp.compareTo(b.timestamp));
}