← 中文资源

简体中文版本

matchAll 与命名捕获组解析日志

用命名捕获组配合 matchAll 解析日志行:每次命中都带自说明的字段名,避免脆弱的下标访问,不匹配的行直接跳过,适合逐行提取结构化字段。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

09:30:01 [INFO] cache warmed in 42ms
09:30:07 [WARN] retry budget at 80%
09:31:00 [ERROR] upstream timeout
parsed 3 of 4 lines

实现说明

重复被限制在 for (const { time, level, message } of entries) 里——其余代码按顺序各跑一遍。 pattern、logText、entries 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 跑完文件,输出里会留下标记——parsed。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件的状态由几个模块级绑定持有:pattern、logText、entries。

核心语句

const entries = [...logText.matchAll(pattern)].map(({ groups }) => ({
  time: groups.time,
  level: groups.level,
  message: groups.message,
}));

代码示例

// 命名捕获组 + matchAll:每条命中都带自说明的字段名
const pattern = /(?<time>\d{2}:\d{2}:\d{2}) (?<level>INFO|WARN|ERROR) (?<message>.+)/g;

const logText = `09:30:01 INFO cache warmed in 42ms
09:30:07 WARN retry budget at 80%
09:31:00 ERROR upstream timeout
not a log line`;

const entries = [...logText.matchAll(pattern)].map(({ groups }) => ({
  time: groups.time,
  level: groups.level,
  message: groups.message,
}));

for (const { time, level, message } of entries) {
  console.log(time, '[' + level + ']', message);
}

// 命名组让下游代码免于脆弱的下标访问;不匹配的行直接被跳过
console.log('parsed', entries.length, 'of 4 lines');