任务
把消息中的数字、十六进制串与 id 替换成占位符,以“错误名 + 归一化消息”作为指纹聚合并计数。
契约
- 输入:JSON 对象:{ errors: [{ name, message }] }
- 输出:JSON 对象数组:[{ fingerprint, count }],按次数降序、再按指纹排序
样例
- 输入
{"errors":[{"name":"TimeoutError","message":"request 8f3a1b2c timed out after 30s"},{"name":"TimeoutError","message":"request 19ac77de timed out after 30s"},{"name":"TypeError","message":"cannot read property of undefined"}]}-> 期望[{"fingerprint":"TimeoutError:request <hex> timed out after <n>s","count":2},{"fingerprint":"TypeError:cannot read property of undefined","count":1}]。两条超时消息的 id 与耗时不同,但归一化后得到同一个指纹。 - 输入
{"errors":[{"name":"ValidationError","message":"field age must be >= 18"},{"name":"ValidationError","message":"field age must be >= 21"}]}-> 期望[{"fingerprint":"ValidationError:field age must be >= <n>","count":2}]。数字被替换掉,同一条校验规则因此被归到一起。
参考实现
function solve({ errors }) {
const normalize = (message) =>
String(message)
.replace(/0x[0-9a-f]+/gi, '<hex>')
.replace(/\b[0-9a-f]{6,}\b/gi, '<hex>')
.replace(/\d+/g, '<n>');
const groups = new Map();
for (const error of errors) {
const fingerprint = error.name + ':' + normalize(error.message);
groups.set(fingerprint, (groups.get(fingerprint) ?? 0) + 1);
}
return [...groups.entries()]
.map(([fingerprint, count]) => ({ fingerprint, count }))
.sort((a, b) => b.count - a.count || a.fingerprint.localeCompare(b.fingerprint));
}
为什么有效
告警疲劳往往来自把每一次错误实例都当成独立事件。指纹化能把同一种缺陷的多次上报收敛成一个可处理的分组。
先归一化再计数;把单词内部的数字一并替换是可以接受的,只要规则前后一致。