@be-link/cls-logger 1.0.1-beta.17 → 1.0.1-beta.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mini.esm.js CHANGED
@@ -178,6 +178,9 @@ class ClsLoggerCore {
178
178
  this.batchTimerDueAt = null;
179
179
  this.initTs = 0;
180
180
  this.startupDelayMs = 0;
181
+ this.useIdleCallback = false;
182
+ this.idleTimeout = 3000;
183
+ this.visibilityCleanup = null;
181
184
  // 参考文档:失败缓存 + 重试
182
185
  this.failedCacheKey = 'cls_failed_logs';
183
186
  this.failedCacheMax = 200;
@@ -247,6 +250,8 @@ class ClsLoggerCore {
247
250
  this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
248
251
  this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
249
252
  this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
253
+ this.useIdleCallback = options.batch?.useIdleCallback ?? this.useIdleCallback;
254
+ this.idleTimeout = options.batch?.idleTimeout ?? this.idleTimeout;
250
255
  this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
251
256
  this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
252
257
  // 预热(避免首条日志触发 import/初始化开销)
@@ -256,6 +261,8 @@ class ClsLoggerCore {
256
261
  if (this.enabled) {
257
262
  // 启动时尝试发送失败缓存
258
263
  this.flushFailed();
264
+ // 添加页面可见性监听(确保页面关闭时数据不丢失)
265
+ this.setupVisibilityListener();
259
266
  // 初始化后立即启动请求监听
260
267
  this.startRequestMonitor(options.requestMonitor);
261
268
  // 初始化后立即启动错误监控/性能监控
@@ -292,6 +299,89 @@ class ClsLoggerCore {
292
299
  return auto;
293
300
  return undefined;
294
301
  }
302
+ /**
303
+ * 设置页面可见性监听
304
+ * - visibilitychange: 页面隐藏时使用 sendBeacon 发送队列
305
+ * - pagehide: 作为移动端 fallback
306
+ */
307
+ setupVisibilityListener() {
308
+ if (typeof document === 'undefined' || typeof window === 'undefined')
309
+ return;
310
+ // 避免重复监听
311
+ if (this.visibilityCleanup)
312
+ return;
313
+ const handleVisibilityChange = () => {
314
+ if (document.visibilityState === 'hidden') {
315
+ this.flushBatchSync();
316
+ }
317
+ };
318
+ const handlePageHide = () => {
319
+ this.flushBatchSync();
320
+ };
321
+ document.addEventListener('visibilitychange', handleVisibilityChange);
322
+ window.addEventListener('pagehide', handlePageHide);
323
+ this.visibilityCleanup = () => {
324
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
325
+ window.removeEventListener('pagehide', handlePageHide);
326
+ };
327
+ }
328
+ /**
329
+ * 同步发送内存队列(使用 sendBeacon)
330
+ * - 用于页面关闭时确保数据发送
331
+ * - sendBeacon 不可用时降级为缓存到 localStorage
332
+ */
333
+ flushBatchSync() {
334
+ if (this.memoryQueue.length === 0)
335
+ return;
336
+ // 清除定时器
337
+ if (this.batchTimer) {
338
+ try {
339
+ if (this.useIdleCallback && typeof cancelIdleCallback !== 'undefined') {
340
+ cancelIdleCallback(this.batchTimer);
341
+ }
342
+ else {
343
+ clearTimeout(this.batchTimer);
344
+ }
345
+ }
346
+ catch {
347
+ // ignore
348
+ }
349
+ this.batchTimer = null;
350
+ }
351
+ this.batchTimerDueAt = null;
352
+ const logs = [...this.memoryQueue];
353
+ this.memoryQueue = [];
354
+ // 优先使用 sendBeacon(页面关闭时可靠发送)
355
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
356
+ try {
357
+ const payload = this.buildSendBeaconPayload(logs);
358
+ const blob = new Blob([payload], { type: 'application/json' });
359
+ const url = `${this.endpoint}/structuredlog?topic_id=${this.topicId}`;
360
+ const success = navigator.sendBeacon(url, blob);
361
+ if (!success) {
362
+ // sendBeacon 返回 false 时,降级缓存
363
+ this.cacheFailedReportLogs(logs);
364
+ }
365
+ }
366
+ catch {
367
+ this.cacheFailedReportLogs(logs);
368
+ }
369
+ }
370
+ else {
371
+ // 不支持 sendBeacon,降级缓存到 localStorage
372
+ this.cacheFailedReportLogs(logs);
373
+ }
374
+ }
375
+ /**
376
+ * 构建 sendBeacon 的 payload
377
+ */
378
+ buildSendBeaconPayload(logs) {
379
+ const logList = logs.map((log) => this.buildReportFields(log));
380
+ return JSON.stringify({
381
+ source: this.source,
382
+ logs: logList,
383
+ });
384
+ }
295
385
  startRequestMonitor(requestMonitor) {
296
386
  if (this.requestMonitorStarted)
297
387
  return;
@@ -546,25 +636,55 @@ class ClsLoggerCore {
546
636
  const desiredDelay = Math.max(0, desiredDueAt - now);
547
637
  if (!this.batchTimer) {
548
638
  this.batchTimerDueAt = desiredDueAt;
549
- this.batchTimer = setTimeout(() => {
550
- void this.flushBatch();
551
- }, desiredDelay);
639
+ this.scheduleFlush(desiredDelay);
552
640
  return;
553
641
  }
554
- // 启动合并窗口内:如果当前 timer 会“更早”触发,则延后到窗口结束,尽量减少多次发送
642
+ // 启动合并窗口内:如果当前 timer 会"更早"触发,则延后到窗口结束,尽量减少多次发送
555
643
  if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
556
- try {
557
- clearTimeout(this.batchTimer);
558
- }
559
- catch {
560
- // ignore
561
- }
644
+ this.cancelScheduledFlush();
562
645
  this.batchTimerDueAt = desiredDueAt;
646
+ this.scheduleFlush(desiredDelay);
647
+ }
648
+ }
649
+ /**
650
+ * 调度批量发送
651
+ * - 支持 requestIdleCallback(浏览器空闲时执行)
652
+ * - 降级为 setTimeout
653
+ */
654
+ scheduleFlush(desiredDelay) {
655
+ if (this.useIdleCallback && typeof requestIdleCallback !== 'undefined') {
656
+ // 使用 requestIdleCallback,设置 timeout 保证最终执行
657
+ const idleId = requestIdleCallback(() => {
658
+ void this.flushBatch();
659
+ }, { timeout: Math.max(desiredDelay, this.idleTimeout) });
660
+ // 存储 idleId 以便清理(类型兼容处理)
661
+ this.batchTimer = idleId;
662
+ }
663
+ else {
563
664
  this.batchTimer = setTimeout(() => {
564
665
  void this.flushBatch();
565
666
  }, desiredDelay);
566
667
  }
567
668
  }
669
+ /**
670
+ * 取消已调度的批量发送
671
+ */
672
+ cancelScheduledFlush() {
673
+ if (!this.batchTimer)
674
+ return;
675
+ try {
676
+ if (this.useIdleCallback && typeof cancelIdleCallback !== 'undefined') {
677
+ cancelIdleCallback(this.batchTimer);
678
+ }
679
+ else {
680
+ clearTimeout(this.batchTimer);
681
+ }
682
+ }
683
+ catch {
684
+ // ignore
685
+ }
686
+ this.batchTimer = null;
687
+ }
568
688
  getDesiredBatchFlushDueAt(nowTs) {
569
689
  const start = this.initTs || nowTs;
570
690
  const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
@@ -575,7 +695,7 @@ class ClsLoggerCore {
575
695
  }
576
696
  return nowTs + this.batchIntervalMs;
577
697
  }
578
- info(message, data = {}) {
698
+ info(message, data = {}, options) {
579
699
  let msg = '';
580
700
  let extra = {};
581
701
  if (message instanceof Error) {
@@ -591,9 +711,18 @@ class ClsLoggerCore {
591
711
  extra = data;
592
712
  }
593
713
  const payload = normalizeFlatFields({ message: msg, ...extra }, 'info');
594
- this.report({ type: 'info', data: payload, timestamp: Date.now() });
714
+ const log = { type: 'info', data: payload, timestamp: Date.now() };
715
+ // info 默认走批量队列,支持 immediate 选项立即发送
716
+ if (options?.immediate) {
717
+ void this.sendReportLogs([log]).catch(() => {
718
+ this.cacheFailedReportLogs([log]);
719
+ });
720
+ }
721
+ else {
722
+ this.report(log);
723
+ }
595
724
  }
596
- warn(message, data = {}) {
725
+ warn(message, data = {}, options) {
597
726
  let msg = '';
598
727
  let extra = {};
599
728
  if (message instanceof Error) {
@@ -609,9 +738,18 @@ class ClsLoggerCore {
609
738
  extra = data;
610
739
  }
611
740
  const payload = normalizeFlatFields({ message: msg, ...extra }, 'warn');
612
- this.report({ type: 'warn', data: payload, timestamp: Date.now() });
741
+ const log = { type: 'warn', data: payload, timestamp: Date.now() };
742
+ // warn 默认走批量队列,支持 immediate 选项立即发送
743
+ if (options?.immediate) {
744
+ void this.sendReportLogs([log]).catch(() => {
745
+ this.cacheFailedReportLogs([log]);
746
+ });
747
+ }
748
+ else {
749
+ this.report(log);
750
+ }
613
751
  }
614
- error(message, data = {}) {
752
+ error(message, data = {}, options) {
615
753
  let msg = '';
616
754
  let extra = {};
617
755
  if (message instanceof Error) {
@@ -627,7 +765,17 @@ class ClsLoggerCore {
627
765
  extra = data;
628
766
  }
629
767
  const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
630
- this.report({ type: 'error', data: payload, timestamp: Date.now() });
768
+ const log = { type: 'error', data: payload, timestamp: Date.now() };
769
+ // error 默认即时上报,除非显式指定 immediate: false
770
+ const immediate = options?.immediate ?? true;
771
+ if (immediate) {
772
+ void this.sendReportLogs([log]).catch(() => {
773
+ this.cacheFailedReportLogs([log]);
774
+ });
775
+ }
776
+ else {
777
+ this.report(log);
778
+ }
631
779
  }
632
780
  track(trackType, data = {}) {
633
781
  if (!trackType)
@@ -642,10 +790,7 @@ class ClsLoggerCore {
642
790
  * 立即发送内存队列
643
791
  */
644
792
  async flushBatch() {
645
- if (this.batchTimer) {
646
- clearTimeout(this.batchTimer);
647
- this.batchTimer = null;
648
- }
793
+ this.cancelScheduledFlush();
649
794
  this.batchTimerDueAt = null;
650
795
  if (this.memoryQueue.length === 0)
651
796
  return;
@@ -987,6 +1132,13 @@ function installMiniRequestMonitor(report, opts = {}) {
987
1132
  const DEFAULT_MAX_TEXT = 4000;
988
1133
  const DEFAULT_DEDUPE_WINDOW_MS = 3000;
989
1134
  const DEFAULT_DEDUPE_MAX_KEYS = 200;
1135
+ /** 默认忽略的无意义错误信息 */
1136
+ const DEFAULT_IGNORE_MESSAGES = [
1137
+ 'Script error.',
1138
+ 'Script error',
1139
+ /^ResizeObserver loop/,
1140
+ 'Permission was denied',
1141
+ ];
990
1142
  function truncate(s, maxLen) {
991
1143
  if (!s)
992
1144
  return s;
@@ -999,6 +1151,17 @@ function sampleHit$1(sampleRate) {
999
1151
  return false;
1000
1152
  return Math.random() < sampleRate;
1001
1153
  }
1154
+ /** 检查消息是否应该被忽略 */
1155
+ function shouldIgnoreMessage(message, ignorePatterns) {
1156
+ if (!message || ignorePatterns.length === 0)
1157
+ return false;
1158
+ return ignorePatterns.some((pattern) => {
1159
+ if (typeof pattern === 'string') {
1160
+ return message === pattern || message.includes(pattern);
1161
+ }
1162
+ return pattern.test(message);
1163
+ });
1164
+ }
1002
1165
  function getMpPagePath() {
1003
1166
  try {
1004
1167
  const pages = globalThis.getCurrentPages?.();
@@ -1093,6 +1256,9 @@ function installMiniProgramErrorMonitor(report, options) {
1093
1256
  if (!sampleHit$1(options.sampleRate))
1094
1257
  return;
1095
1258
  const e = normalizeErrorLike(msg, options.maxTextLength);
1259
+ // 检查是否应该忽略此错误
1260
+ if (shouldIgnoreMessage(e.message, options.ignoreMessages))
1261
+ return;
1096
1262
  const payload = {
1097
1263
  pagePath: getMpPagePath(),
1098
1264
  source: 'wx.onError',
@@ -1120,6 +1286,9 @@ function installMiniProgramErrorMonitor(report, options) {
1120
1286
  if (!sampleHit$1(options.sampleRate))
1121
1287
  return;
1122
1288
  const e = normalizeErrorLike(res?.reason, options.maxTextLength);
1289
+ // 检查是否应该忽略此错误
1290
+ if (shouldIgnoreMessage(e.message, options.ignoreMessages))
1291
+ return;
1123
1292
  const payload = {
1124
1293
  pagePath: getMpPagePath(),
1125
1294
  source: 'wx.onUnhandledRejection',
@@ -1151,15 +1320,18 @@ function installMiniProgramErrorMonitor(report, options) {
1151
1320
  try {
1152
1321
  if (sampleHit$1(options.sampleRate)) {
1153
1322
  const e = normalizeErrorLike(args?.[0], options.maxTextLength);
1154
- const payload = {
1155
- pagePath: getMpPagePath(),
1156
- source: 'App.onError',
1157
- message: e.message,
1158
- errorName: e.name,
1159
- stack: e.stack,
1160
- };
1161
- if (shouldReport(buildErrorKey(options.reportType, payload)))
1162
- report(options.reportType, payload);
1323
+ // 检查是否应该忽略此错误
1324
+ if (!shouldIgnoreMessage(e.message, options.ignoreMessages)) {
1325
+ const payload = {
1326
+ pagePath: getMpPagePath(),
1327
+ source: 'App.onError',
1328
+ message: e.message,
1329
+ errorName: e.name,
1330
+ stack: e.stack,
1331
+ };
1332
+ if (shouldReport(buildErrorKey(options.reportType, payload)))
1333
+ report(options.reportType, payload);
1334
+ }
1163
1335
  }
1164
1336
  }
1165
1337
  catch {
@@ -1175,15 +1347,18 @@ function installMiniProgramErrorMonitor(report, options) {
1175
1347
  if (sampleHit$1(options.sampleRate)) {
1176
1348
  const reason = args?.[0]?.reason ?? args?.[0];
1177
1349
  const e = normalizeErrorLike(reason, options.maxTextLength);
1178
- const payload = {
1179
- pagePath: getMpPagePath(),
1180
- source: 'App.onUnhandledRejection',
1181
- message: e.message,
1182
- errorName: e.name,
1183
- stack: e.stack,
1184
- };
1185
- if (shouldReport(buildErrorKey(options.reportType, payload)))
1186
- report(options.reportType, payload);
1350
+ // 检查是否应该忽略此错误
1351
+ if (!shouldIgnoreMessage(e.message, options.ignoreMessages)) {
1352
+ const payload = {
1353
+ pagePath: getMpPagePath(),
1354
+ source: 'App.onUnhandledRejection',
1355
+ message: e.message,
1356
+ errorName: e.name,
1357
+ stack: e.stack,
1358
+ };
1359
+ if (shouldReport(buildErrorKey(options.reportType, payload)))
1360
+ report(options.reportType, payload);
1361
+ }
1187
1362
  }
1188
1363
  }
1189
1364
  catch {
@@ -1214,6 +1389,7 @@ function installMiniErrorMonitor(report, opts = {}) {
1214
1389
  maxTextLength: raw.maxTextLength ?? DEFAULT_MAX_TEXT,
1215
1390
  dedupeWindowMs: raw.dedupeWindowMs ?? DEFAULT_DEDUPE_WINDOW_MS,
1216
1391
  dedupeMaxKeys: raw.dedupeMaxKeys ?? DEFAULT_DEDUPE_MAX_KEYS,
1392
+ ignoreMessages: raw.ignoreMessages ?? DEFAULT_IGNORE_MESSAGES,
1217
1393
  };
1218
1394
  installMiniProgramErrorMonitor(report, options);
1219
1395
  }