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

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/web.js CHANGED
@@ -201,6 +201,9 @@ class ClsLoggerCore {
201
201
  this.batchTimerDueAt = null;
202
202
  this.initTs = 0;
203
203
  this.startupDelayMs = 0;
204
+ this.useIdleCallback = false;
205
+ this.idleTimeout = 3000;
206
+ this.visibilityCleanup = null;
204
207
  // 参考文档:失败缓存 + 重试
205
208
  this.failedCacheKey = 'cls_failed_logs';
206
209
  this.failedCacheMax = 200;
@@ -270,6 +273,8 @@ class ClsLoggerCore {
270
273
  this.batchMaxSize = options.batch?.maxSize ?? this.batchMaxSize;
271
274
  this.batchIntervalMs = options.batch?.intervalMs ?? this.batchIntervalMs;
272
275
  this.startupDelayMs = options.batch?.startupDelayMs ?? this.startupDelayMs;
276
+ this.useIdleCallback = options.batch?.useIdleCallback ?? this.useIdleCallback;
277
+ this.idleTimeout = options.batch?.idleTimeout ?? this.idleTimeout;
273
278
  this.failedCacheKey = options.failedCacheKey ?? this.failedCacheKey;
274
279
  this.failedCacheMax = options.failedCacheMax ?? this.failedCacheMax;
275
280
  // 预热(避免首条日志触发 import/初始化开销)
@@ -279,6 +284,8 @@ class ClsLoggerCore {
279
284
  if (this.enabled) {
280
285
  // 启动时尝试发送失败缓存
281
286
  this.flushFailed();
287
+ // 添加页面可见性监听(确保页面关闭时数据不丢失)
288
+ this.setupVisibilityListener();
282
289
  // 初始化后立即启动请求监听
283
290
  this.startRequestMonitor(options.requestMonitor);
284
291
  // 初始化后立即启动错误监控/性能监控
@@ -315,6 +322,89 @@ class ClsLoggerCore {
315
322
  return auto;
316
323
  return undefined;
317
324
  }
325
+ /**
326
+ * 设置页面可见性监听
327
+ * - visibilitychange: 页面隐藏时使用 sendBeacon 发送队列
328
+ * - pagehide: 作为移动端 fallback
329
+ */
330
+ setupVisibilityListener() {
331
+ if (typeof document === 'undefined' || typeof window === 'undefined')
332
+ return;
333
+ // 避免重复监听
334
+ if (this.visibilityCleanup)
335
+ return;
336
+ const handleVisibilityChange = () => {
337
+ if (document.visibilityState === 'hidden') {
338
+ this.flushBatchSync();
339
+ }
340
+ };
341
+ const handlePageHide = () => {
342
+ this.flushBatchSync();
343
+ };
344
+ document.addEventListener('visibilitychange', handleVisibilityChange);
345
+ window.addEventListener('pagehide', handlePageHide);
346
+ this.visibilityCleanup = () => {
347
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
348
+ window.removeEventListener('pagehide', handlePageHide);
349
+ };
350
+ }
351
+ /**
352
+ * 同步发送内存队列(使用 sendBeacon)
353
+ * - 用于页面关闭时确保数据发送
354
+ * - sendBeacon 不可用时降级为缓存到 localStorage
355
+ */
356
+ flushBatchSync() {
357
+ if (this.memoryQueue.length === 0)
358
+ return;
359
+ // 清除定时器
360
+ if (this.batchTimer) {
361
+ try {
362
+ if (this.useIdleCallback && typeof cancelIdleCallback !== 'undefined') {
363
+ cancelIdleCallback(this.batchTimer);
364
+ }
365
+ else {
366
+ clearTimeout(this.batchTimer);
367
+ }
368
+ }
369
+ catch {
370
+ // ignore
371
+ }
372
+ this.batchTimer = null;
373
+ }
374
+ this.batchTimerDueAt = null;
375
+ const logs = [...this.memoryQueue];
376
+ this.memoryQueue = [];
377
+ // 优先使用 sendBeacon(页面关闭时可靠发送)
378
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
379
+ try {
380
+ const payload = this.buildSendBeaconPayload(logs);
381
+ const blob = new Blob([payload], { type: 'application/json' });
382
+ const url = `${this.endpoint}/structuredlog?topic_id=${this.topicId}`;
383
+ const success = navigator.sendBeacon(url, blob);
384
+ if (!success) {
385
+ // sendBeacon 返回 false 时,降级缓存
386
+ this.cacheFailedReportLogs(logs);
387
+ }
388
+ }
389
+ catch {
390
+ this.cacheFailedReportLogs(logs);
391
+ }
392
+ }
393
+ else {
394
+ // 不支持 sendBeacon,降级缓存到 localStorage
395
+ this.cacheFailedReportLogs(logs);
396
+ }
397
+ }
398
+ /**
399
+ * 构建 sendBeacon 的 payload
400
+ */
401
+ buildSendBeaconPayload(logs) {
402
+ const logList = logs.map((log) => this.buildReportFields(log));
403
+ return JSON.stringify({
404
+ source: this.source,
405
+ logs: logList,
406
+ });
407
+ }
318
408
  startRequestMonitor(requestMonitor) {
319
409
  if (this.requestMonitorStarted)
320
410
  return;
@@ -569,25 +659,55 @@ class ClsLoggerCore {
569
659
  const desiredDelay = Math.max(0, desiredDueAt - now);
570
660
  if (!this.batchTimer) {
571
661
  this.batchTimerDueAt = desiredDueAt;
572
- this.batchTimer = setTimeout(() => {
573
- void this.flushBatch();
574
- }, desiredDelay);
662
+ this.scheduleFlush(desiredDelay);
575
663
  return;
576
664
  }
577
- // 启动合并窗口内:如果当前 timer 会“更早”触发,则延后到窗口结束,尽量减少多次发送
665
+ // 启动合并窗口内:如果当前 timer 会"更早"触发,则延后到窗口结束,尽量减少多次发送
578
666
  if (this.batchTimerDueAt !== null && this.batchTimerDueAt < desiredDueAt) {
579
- try {
580
- clearTimeout(this.batchTimer);
581
- }
582
- catch {
583
- // ignore
584
- }
667
+ this.cancelScheduledFlush();
585
668
  this.batchTimerDueAt = desiredDueAt;
669
+ this.scheduleFlush(desiredDelay);
670
+ }
671
+ }
672
+ /**
673
+ * 调度批量发送
674
+ * - 支持 requestIdleCallback(浏览器空闲时执行)
675
+ * - 降级为 setTimeout
676
+ */
677
+ scheduleFlush(desiredDelay) {
678
+ if (this.useIdleCallback && typeof requestIdleCallback !== 'undefined') {
679
+ // 使用 requestIdleCallback,设置 timeout 保证最终执行
680
+ const idleId = requestIdleCallback(() => {
681
+ void this.flushBatch();
682
+ }, { timeout: Math.max(desiredDelay, this.idleTimeout) });
683
+ // 存储 idleId 以便清理(类型兼容处理)
684
+ this.batchTimer = idleId;
685
+ }
686
+ else {
586
687
  this.batchTimer = setTimeout(() => {
587
688
  void this.flushBatch();
588
689
  }, desiredDelay);
589
690
  }
590
691
  }
692
+ /**
693
+ * 取消已调度的批量发送
694
+ */
695
+ cancelScheduledFlush() {
696
+ if (!this.batchTimer)
697
+ return;
698
+ try {
699
+ if (this.useIdleCallback && typeof cancelIdleCallback !== 'undefined') {
700
+ cancelIdleCallback(this.batchTimer);
701
+ }
702
+ else {
703
+ clearTimeout(this.batchTimer);
704
+ }
705
+ }
706
+ catch {
707
+ // ignore
708
+ }
709
+ this.batchTimer = null;
710
+ }
591
711
  getDesiredBatchFlushDueAt(nowTs) {
592
712
  const start = this.initTs || nowTs;
593
713
  const startupDelay = Number.isFinite(this.startupDelayMs) ? Math.max(0, this.startupDelayMs) : 0;
@@ -598,7 +718,7 @@ class ClsLoggerCore {
598
718
  }
599
719
  return nowTs + this.batchIntervalMs;
600
720
  }
601
- info(message, data = {}) {
721
+ info(message, data = {}, options) {
602
722
  let msg = '';
603
723
  let extra = {};
604
724
  if (message instanceof Error) {
@@ -614,9 +734,18 @@ class ClsLoggerCore {
614
734
  extra = data;
615
735
  }
616
736
  const payload = normalizeFlatFields({ message: msg, ...extra }, 'info');
617
- this.report({ type: 'info', data: payload, timestamp: Date.now() });
737
+ const log = { type: 'info', data: payload, timestamp: Date.now() };
738
+ // info 默认走批量队列,支持 immediate 选项立即发送
739
+ if (options?.immediate) {
740
+ void this.sendReportLogs([log]).catch(() => {
741
+ this.cacheFailedReportLogs([log]);
742
+ });
743
+ }
744
+ else {
745
+ this.report(log);
746
+ }
618
747
  }
619
- warn(message, data = {}) {
748
+ warn(message, data = {}, options) {
620
749
  let msg = '';
621
750
  let extra = {};
622
751
  if (message instanceof Error) {
@@ -632,9 +761,18 @@ class ClsLoggerCore {
632
761
  extra = data;
633
762
  }
634
763
  const payload = normalizeFlatFields({ message: msg, ...extra }, 'warn');
635
- this.report({ type: 'warn', data: payload, timestamp: Date.now() });
764
+ const log = { type: 'warn', data: payload, timestamp: Date.now() };
765
+ // warn 默认走批量队列,支持 immediate 选项立即发送
766
+ if (options?.immediate) {
767
+ void this.sendReportLogs([log]).catch(() => {
768
+ this.cacheFailedReportLogs([log]);
769
+ });
770
+ }
771
+ else {
772
+ this.report(log);
773
+ }
636
774
  }
637
- error(message, data = {}) {
775
+ error(message, data = {}, options) {
638
776
  let msg = '';
639
777
  let extra = {};
640
778
  if (message instanceof Error) {
@@ -650,7 +788,17 @@ class ClsLoggerCore {
650
788
  extra = data;
651
789
  }
652
790
  const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
653
- this.report({ type: 'error', data: payload, timestamp: Date.now() });
791
+ const log = { type: 'error', data: payload, timestamp: Date.now() };
792
+ // error 默认即时上报,除非显式指定 immediate: false
793
+ const immediate = options?.immediate ?? true;
794
+ if (immediate) {
795
+ void this.sendReportLogs([log]).catch(() => {
796
+ this.cacheFailedReportLogs([log]);
797
+ });
798
+ }
799
+ else {
800
+ this.report(log);
801
+ }
654
802
  }
655
803
  track(trackType, data = {}) {
656
804
  if (!trackType)
@@ -665,10 +813,7 @@ class ClsLoggerCore {
665
813
  * 立即发送内存队列
666
814
  */
667
815
  async flushBatch() {
668
- if (this.batchTimer) {
669
- clearTimeout(this.batchTimer);
670
- this.batchTimer = null;
671
- }
816
+ this.cancelScheduledFlush();
672
817
  this.batchTimerDueAt = null;
673
818
  if (this.memoryQueue.length === 0)
674
819
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@be-link/cls-logger",
3
- "version": "1.0.1-beta.17",
3
+ "version": "1.0.1-beta.18",
4
4
  "description": "@be-link cls-logger - 腾讯云 CLS 日志上报封装",
5
5
  "homepage": "https://github.com/snowmountain-top/be-link",
6
6
  "author": "zhuiyi",