@be-link/cls-logger 1.0.1-beta.8 → 1.0.3

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @be-link/cls-logger
2
2
 
3
- 腾讯云 CLS(`tencentcloud-cls-sdk-js-web`)日志上报封装,参考仓库内 `@be-link/utils` 的构建方式(Rollup 打包 + tsc 仅产出 d.ts)。
3
+ 腾讯云 CLS(`tencentcloud-cls-sdk-js-web` / `tencentcloud-cls-sdk-js-mini`)日志上报封装,支持 Web、H5 和小程序环境,提供统一的调用方式。
4
4
 
5
5
  ## 安装
6
6
 
@@ -8,58 +8,92 @@
8
8
  pnpm add @be-link/cls-logger
9
9
  ```
10
10
 
11
+ > 依赖说明:本包依赖了腾讯云的 Web 和小程序 SDK。在使用时,内部会自动根据运行环境加载对应的 SDK。
12
+
11
13
  ## 使用
12
14
 
15
+ **统一引入方式**,无需关心运行环境(Web 或 小程序),SDK 内部会自动识别并适配。
16
+
13
17
  ```ts
14
- import clsLogger, { ClsLogger } from '@be-link/cls-logger';
18
+ import clsLogger from '@be-link/cls-logger';
15
19
 
20
+ // 1. 初始化(建议在应用入口处调用)
16
21
  clsLogger.init({
17
- topic_id: 'xxx',
22
+ topic_id: 'xxx', // 你的 CLS Topic ID
18
23
  projectName: 'my-project',
24
+ // 可选:环境信息(内部会自动采集,这里可以补充业务相关基础字段)
19
25
  generateBaseFields: () => ({ env: 'prod', uid: 'u_1' }),
20
26
  });
21
27
 
22
- // 直接上报(展开字段)
23
- clsLogger.put({ event: 'login', ok: true });
28
+ // 2. 日志上报
29
+ // Info 日志
30
+ clsLogger.info('应用启动', { startUpTime: 120 });
31
+
32
+ // Error 日志(支持直接传入 Error 对象,自动解析堆栈)
33
+ try {
34
+ doSomething();
35
+ } catch (err) {
36
+ clsLogger.error(err, { module: 'payment' });
37
+ }
38
+
39
+ // 3. 自定义埋点 (Track)
40
+ clsLogger.track('click_event', {
41
+ button: 'submit',
42
+ page: '/home',
43
+ });
44
+ ```
45
+
46
+ ## 功能特性
47
+
48
+ ### 1. 自动环境适配
49
+
50
+ - **Web / H5**: 自动加载 `tencentcloud-cls-sdk-js-web`,采集浏览器环境信息(UserAgent、Web Vitals 等)。
51
+ - **小程序**: 自动加载 `tencentcloud-cls-sdk-js-mini`,适配 `wx.request`,采集小程序环境信息(SystemInfo、NetworkType 等)。
52
+
53
+ ### 2. 请求监控 (Request Monitor)
24
54
 
25
- // 直接上报(JSON 放进单个 key,默认 “日志内容”)
26
- clsLogger.putJson({ event: 'click', x: 1, y: 2 });
55
+ 默认开启 HTTP 请求监控。
27
56
 
28
- // 入队(写入 localStorage,默认 15 条自动 flush)
29
- clsLogger.enqueue({ event: 'page_view', page: '/home' });
57
+ - Web: 拦截 `fetch` / `XMLHttpRequest`
58
+ - 小程序: 拦截 `wx.request` / `wx.cloud.callFunction`
59
+
60
+ 如需关闭或配置:
61
+
62
+ ```ts
63
+ clsLogger.init({
64
+ requestMonitor: {
65
+ enabled: true,
66
+ ignoreUrls: ['example.com', /login/], // 忽略特定 URL
67
+ },
68
+ });
30
69
  ```
31
70
 
32
- ## 请求监控(requestMonitor)
71
+ ### 3. 性能监控 (Performance Monitor)
72
+
73
+ 默认开启性能指标采集。
74
+
75
+ - Web: 采集 FCP, LCP, CLS, FID 等 Core Web Vitals 及资源加载耗时。
76
+ - 小程序: 暂不支持性能指标自动采集。
33
77
 
34
- 初始化后默认会开启 HTTP 请求监控(Web/H5:`fetch`/`XMLHttpRequest`;小程序:`wx.request`/`cloud.callFunction`),并把请求信息通过 `track('http', payload)` 上报。
78
+ ### 4. 行为埋点 (Behavior Monitor)
35
79
 
36
- - **关闭**:`clsLogger.init({ requestMonitor: false })`
37
- - **忽略上报请求避免递归**:默认会忽略 CLS 上报域名(会把 `endpoint` 自动加入 `ignoreUrls`),并在内部增加了“上报发送”保护,避免上报请求在跨域失败时出现递归上报/死循环。
38
- - **自定义忽略**:`clsLogger.init({ requestMonitor: { ignoreUrls: ['example.com', /\\/internal\\//] } })`
80
+ 默认开启,支持 PV (Page View) UV (User View) 自动上报。
39
81
 
40
- ## 性能监控(performanceMonitor)
82
+ - 自动生成/持久化 UV ID。
83
+ - 支持点击事件自动上报(需配置)。
41
84
 
42
- 初始化后默认会开启性能监控,并通过 `track('perf', payload)` 上报,包含:
85
+ ## 高级用法
43
86
 
44
- - **Web Vitals**:FCP/LCP/CLS/FID
45
- - **Navigation Timing**:TTFB 等
46
- - **Resource Timing**:资源加载耗时(`PerformanceObserver({ type: 'resource', buffered: true })`,首屏会比较多)
87
+ ### 手动注入 SDK
47
88
 
48
- 常见降噪配置:
89
+ 在某些特殊构建环境(如某些不允许动态 require 的小程序框架)下,如果自动加载 SDK 失败,可以手动注入:
49
90
 
50
91
  ```ts
51
92
  import clsLogger from '@be-link/cls-logger';
93
+ import * as MiniSdk from 'tencentcloud-cls-sdk-js-mini';
52
94
 
53
95
  clsLogger.init({
54
96
  topic_id: 'xxx',
55
- projectName: 'my-project',
56
- performanceMonitor: {
57
- // 降低采样(0~1)
58
- sampleRate: 0.1,
59
- // 忽略本地开发资源 & sourcemap(按你的资源特征调整)
60
- ignoreUrls: ['localhost:8080', /\\.map$/],
61
- },
62
- // 可选:启动阶段合并窗口,减少首屏 perf/resource 被 intervalMs 拆成多次上报
63
- // batch: { startupDelayMs: 2000 },
97
+ sdk: MiniSdk, // 手动传入 SDK 实例
64
98
  });
65
99
  ```
@@ -1 +1 @@
1
- {"version":3,"file":"ClsLogger.d.ts","sourceRoot":"","sources":["../src/ClsLogger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAGlD;;;;GAIG;AACH,qBAAa,SAAU,SAAQ,aAAa;cAC1B,OAAO,IAAI,OAAO,CAAC,YAAY,CAAC;CA8EjD"}
1
+ {"version":3,"file":"ClsLogger.d.ts","sourceRoot":"","sources":["../src/ClsLogger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAGlD;;;;GAIG;AACH,qBAAa,SAAU,SAAQ,aAAa;cAC1B,OAAO,IAAI,OAAO,CAAC,YAAY,CAAC;CAkHjD"}
@@ -101,9 +101,9 @@ export declare abstract class ClsLoggerCore {
101
101
  */
102
102
  report(log: ReportLog): void;
103
103
  private getDesiredBatchFlushDueAt;
104
- info(message: string, data?: FlatFields): void;
105
- warn(message: string, data?: FlatFields): void;
106
- error(message: string, data?: FlatFields): void;
104
+ info(message: string | Error, data?: FlatFields): void;
105
+ warn(message: string | Error, data?: FlatFields): void;
106
+ error(message: string | Error, data?: FlatFields): void;
107
107
  track(trackType: string, data?: FlatFields): void;
108
108
  /**
109
109
  * 立即发送内存队列
@@ -1 +1 @@
1
- {"version":3,"file":"ClsLoggerCore.d.ts","sourceRoot":"","sources":["../src/ClsLoggerCore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EAEpB,OAAO,EACP,UAAU,EAEV,UAAU,EACV,SAAS,EACT,SAAS,EAEV,MAAM,SAAS,CAAC;AAgBjB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAYlD;;;;;GAKG;AACH,8BAAsB,aAAa;IACjC,SAAS,CAAC,GAAG,EAAE,YAAY,GAAG,IAAI,CAAQ;IAC1C,SAAS,CAAC,UAAU,EAAE,OAAO,CAAC,YAAY,CAAC,GAAG,IAAI,CAAQ;IAC1D,SAAS,CAAC,WAAW,EAAE,OAAO,GAAG,IAAI,CAAQ;IAC7C,SAAS,CAAC,iBAAiB,EAAE,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAQ;IAC9E,SAAS,CAAC,MAAM,EAAE;QAAE,OAA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 {"version":3,"file":"behaviorMonitor.d.ts","sourceRoot":"","sources":["../src/behaviorMonitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAG3E,KAAK,QAAQ,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,KAAK,IAAI,CAAC;AA8FzD,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,QAAQ,EAChB,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,sBAA2B,GACnC,MAAM,IAAI,CAiXZ"}
@@ -1 +1 @@
1
- {"version":3,"file":"errorMonitor.d.ts","sourceRoot":"","sources":["../src/errorMonitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAG/D,KAAK,QAAQ,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,KAAK,IAAI,CAAC;AA6RzD,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,GAAE,OAAO,GAAG,mBAAmB,GAAG,SAAc,GAAG,IAAI,CAqBhH"}
1
+ {"version":3,"file":"errorMonitor.d.ts","sourceRoot":"","sources":["../src/errorMonitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAG/D,KAAK,QAAQ,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,KAAK,IAAI,CAAC;AA8SzD,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,GAAE,OAAO,GAAG,mBAAmB,GAAG,SAAc,GAAG,IAAI,CAqBhH"}
package/dist/index.esm.js CHANGED
@@ -558,6 +558,19 @@ function getPagePath$1() {
558
558
  return '';
559
559
  }
560
560
  }
561
+ function getMpPagePath() {
562
+ try {
563
+ const pages = globalThis.getCurrentPages?.();
564
+ if (Array.isArray(pages) && pages.length > 0) {
565
+ const page = pages[pages.length - 1];
566
+ return page.route || page.__route__ || '';
567
+ }
568
+ return '';
569
+ }
570
+ catch {
571
+ return '';
572
+ }
573
+ }
561
574
  function normalizeErrorLike(err, maxTextLength) {
562
575
  if (err && typeof err === 'object') {
563
576
  const anyErr = err;
@@ -717,6 +730,7 @@ function installMiniProgramErrorMonitor(report, options) {
717
730
  return;
718
731
  const e = normalizeErrorLike(msg, options.maxTextLength);
719
732
  const payload = {
733
+ pagePath: getMpPagePath(),
720
734
  source: 'wx.onError',
721
735
  message: e.message,
722
736
  errorName: e.name,
@@ -743,6 +757,7 @@ function installMiniProgramErrorMonitor(report, options) {
743
757
  return;
744
758
  const e = normalizeErrorLike(res?.reason, options.maxTextLength);
745
759
  const payload = {
760
+ pagePath: getMpPagePath(),
746
761
  source: 'wx.onUnhandledRejection',
747
762
  message: e.message,
748
763
  errorName: e.name,
@@ -774,6 +789,7 @@ function installMiniProgramErrorMonitor(report, options) {
774
789
  if (sampleHit$1(options.sampleRate)) {
775
790
  const e = normalizeErrorLike(args?.[0], options.maxTextLength);
776
791
  const payload = {
792
+ pagePath: getMpPagePath(),
777
793
  source: 'App.onError',
778
794
  message: e.message,
779
795
  errorName: e.name,
@@ -797,6 +813,7 @@ function installMiniProgramErrorMonitor(report, options) {
797
813
  const reason = args?.[0]?.reason ?? args?.[0];
798
814
  const e = normalizeErrorLike(reason, options.maxTextLength);
799
815
  const payload = {
816
+ pagePath: getMpPagePath(),
800
817
  source: 'App.onUnhandledRejection',
801
818
  message: e.message,
802
819
  errorName: e.name,
@@ -1084,140 +1101,68 @@ function installBrowserPerformanceMonitor(report, options) {
1084
1101
  }
1085
1102
  }
1086
1103
  }
1087
- function wrapMiniProgramRouteApi(report, reportType, apiName, options) {
1088
- const wxAny = globalThis.wx;
1089
- if (!wxAny || typeof wxAny[apiName] !== 'function')
1090
- return;
1091
- const flagKey = `__beLinkClsLoggerMpRouteWrapped__${apiName}`;
1092
- if (wxAny[flagKey])
1093
- return;
1094
- wxAny[flagKey] = true;
1095
- const raw = wxAny[apiName].bind(wxAny);
1096
- wxAny[apiName] = (opts) => {
1097
- const start = Date.now();
1098
- const url = opts?.url ? String(opts.url) : '';
1099
- const wrapCb = (cb, success) => {
1100
- return (...args) => {
1101
- try {
1102
- if (sampleHit(options.sampleRate)) {
1103
- report(reportType, {
1104
- metric: 'route',
1105
- api: apiName,
1106
- url,
1107
- duration: Date.now() - start,
1108
- success: success ? 1 : 0,
1109
- error: success ? '' : truncate$1(stringifyLogValue(args?.[0]), options.maxTextLength),
1110
- unit: 'ms',
1111
- });
1112
- }
1113
- }
1114
- catch {
1115
- // ignore
1116
- }
1117
- if (typeof cb === 'function')
1118
- return cb(...args);
1119
- return undefined;
1120
- };
1121
- };
1122
- const next = { ...(opts ?? {}) };
1123
- next.success = wrapCb(next.success, true);
1124
- next.fail = wrapCb(next.fail, false);
1125
- return raw(next);
1126
- };
1127
- }
1128
- function installMiniProgramPageRenderMonitor(report, reportType, options) {
1129
- const g = globalThis;
1130
- if (typeof g.Page !== 'function')
1131
- return;
1132
- if (g.__beLinkClsLoggerPageWrapped__)
1133
- return;
1134
- g.__beLinkClsLoggerPageWrapped__ = true;
1135
- const rawPage = g.Page;
1136
- g.Page = (pageOptions) => {
1137
- const next = { ...(pageOptions ?? {}) };
1138
- const rawOnLoad = next.onLoad;
1139
- const rawOnReady = next.onReady;
1140
- next.onLoad = function (...args) {
1141
- try {
1142
- this.__beLinkClsLoggerPageLoadTs__ = Date.now();
1143
- }
1144
- catch {
1145
- // ignore
1146
- }
1147
- if (typeof rawOnLoad === 'function')
1148
- return rawOnLoad.apply(this, args);
1149
- return undefined;
1150
- };
1151
- next.onReady = function (...args) {
1152
- try {
1153
- const start = this.__beLinkClsLoggerPageLoadTs__;
1154
- if (typeof start === 'number' && sampleHit(options.sampleRate)) {
1155
- report(reportType, {
1156
- metric: 'page-render',
1157
- route: this?.route ? String(this.route) : '',
1158
- duration: Date.now() - start,
1159
- unit: 'ms',
1160
- });
1161
- }
1162
- }
1163
- catch {
1164
- // ignore
1165
- }
1166
- if (typeof rawOnReady === 'function')
1167
- return rawOnReady.apply(this, args);
1168
- return undefined;
1169
- };
1170
- return rawPage(next);
1171
- };
1172
- }
1173
1104
  function installMiniProgramPerformanceMonitor(report, options) {
1174
1105
  const g = globalThis;
1106
+ const ctx = g.wx || g.Taro;
1107
+ if (!ctx || typeof ctx.getPerformance !== 'function')
1108
+ return;
1175
1109
  if (g.__beLinkClsLoggerMpPerfInstalled__)
1176
1110
  return;
1177
1111
  g.__beLinkClsLoggerMpPerfInstalled__ = true;
1178
- // 路由切换耗时(用 API 回调近似)
1179
- for (const apiName of ['navigateTo', 'redirectTo', 'switchTab', 'reLaunch']) {
1180
- try {
1181
- wrapMiniProgramRouteApi(report, options.reportType, apiName, options);
1182
- }
1183
- catch {
1184
- // ignore
1185
- }
1186
- }
1187
- // 页面渲染耗时(onLoad -> onReady)
1188
1112
  try {
1189
- installMiniProgramPageRenderMonitor(report, options.reportType, options);
1190
- }
1191
- catch {
1192
- // ignore
1193
- }
1194
- // wx.getPerformance()(若可用,尝试读取已有 entries)
1195
- try {
1196
- const wxAny = globalThis.wx;
1197
- if (wxAny && typeof wxAny.getPerformance === 'function') {
1198
- const perf = wxAny.getPerformance();
1199
- if (perf && isPlainObject(perf)) {
1200
- // 不同基础库实现差异较大:尽量容错
1201
- setTimeout(() => {
1202
- try {
1203
- if (!sampleHit(options.sampleRate))
1204
- return;
1205
- const entries = typeof perf.getEntries === 'function'
1206
- ? perf.getEntries()
1207
- : typeof perf.getEntriesByType === 'function'
1208
- ? perf.getEntriesByType('navigation')
1209
- : [];
1113
+ const perf = ctx.getPerformance();
1114
+ if (!perf || typeof perf.createObserver !== 'function')
1115
+ return;
1116
+ const observer = perf.createObserver((entryList) => {
1117
+ try {
1118
+ const entries = entryList.getEntries();
1119
+ for (const entry of entries) {
1120
+ if (!sampleHit(options.sampleRate))
1121
+ continue;
1122
+ // Page Render: firstRender
1123
+ if (entry.entryType === 'render' && entry.name === 'firstRender') {
1124
+ const duration = typeof entry.duration === 'number'
1125
+ ? entry.duration
1126
+ : typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
1127
+ ? entry.endTime - entry.startTime
1128
+ : 0;
1210
1129
  report(options.reportType, {
1211
- metric: 'mp-performance',
1212
- entries: truncate$1(stringifyLogValue(entries), options.maxTextLength),
1130
+ metric: 'page-render',
1131
+ duration,
1132
+ pagePath: entry.path || '',
1133
+ unit: 'ms',
1213
1134
  });
1214
1135
  }
1215
- catch {
1216
- // ignore
1136
+ // Route Switch: route
1137
+ else if (entry.entryType === 'navigation' && entry.name === 'route') {
1138
+ const duration = typeof entry.duration === 'number'
1139
+ ? entry.duration
1140
+ : typeof entry.startTime === 'number' && typeof entry.endTime === 'number'
1141
+ ? entry.endTime - entry.startTime
1142
+ : 0;
1143
+ report(options.reportType, {
1144
+ metric: 'route',
1145
+ duration,
1146
+ pagePath: entry.path || '',
1147
+ unit: 'ms',
1148
+ });
1217
1149
  }
1218
- }, 0);
1150
+ // App Launch: appLaunch (Cold)
1151
+ else if (entry.entryType === 'navigation' && entry.name === 'appLaunch') {
1152
+ report(options.reportType, {
1153
+ metric: 'app-launch',
1154
+ duration: entry.duration,
1155
+ launchType: 'cold',
1156
+ unit: 'ms',
1157
+ });
1158
+ }
1159
+ }
1219
1160
  }
1220
- }
1161
+ catch {
1162
+ // ignore
1163
+ }
1164
+ });
1165
+ observer.observe({ entryTypes: ['navigation', 'render'] });
1221
1166
  }
1222
1167
  catch {
1223
1168
  // ignore
@@ -1541,7 +1486,7 @@ function installBehaviorMonitor(report, envType, options = {}) {
1541
1486
  const tag = (el.tagName || '').toLowerCase();
1542
1487
  const trackId = getAttr(el, clickTrackIdAttr);
1543
1488
  // 过滤无效点击:白名单 tag + 没有 trackId
1544
- if (clickWhiteList.includes(tag) && !trackId)
1489
+ if (clickWhiteList.includes(tag) || !trackId)
1545
1490
  return;
1546
1491
  void uvStatePromise.then(({ uvId, meta }) => {
1547
1492
  if (destroyed)
@@ -1582,8 +1527,12 @@ function installBehaviorMonitor(report, envType, options = {}) {
1582
1527
  g.Page = function patchedPage(conf) {
1583
1528
  const originalOnShow = conf?.onShow;
1584
1529
  conf.onShow = function (...args) {
1585
- if (pvEnabled)
1586
- reportPv(getPagePath());
1530
+ if (pvEnabled) {
1531
+ const pagePath = getPagePath();
1532
+ if (pagePath?.length > 0) {
1533
+ reportPv(pagePath);
1534
+ }
1535
+ }
1587
1536
  return typeof originalOnShow === 'function' ? originalOnShow.apply(this, args) : undefined;
1588
1537
  };
1589
1538
  // 点击:wrap 页面 methods(bindtap 等会调用到这里的 handler)
@@ -1967,9 +1916,14 @@ class ClsLoggerCore {
1967
1916
  * 子类可按需重写(默认检测 wx)
1968
1917
  */
1969
1918
  detectEnvType() {
1970
- const wxAny = globalThis.wx;
1971
- if (wxAny && typeof wxAny.getSystemInfoSync === 'function')
1919
+ const g = globalThis;
1920
+ // 微信、支付宝、字节跳动、UniApp 等小程序环境通常都有特定全局变量
1921
+ if ((g.wx && typeof g.wx.getSystemInfoSync === 'function') ||
1922
+ (g.my && typeof g.my.getSystemInfoSync === 'function') ||
1923
+ (g.tt && typeof g.tt.getSystemInfoSync === 'function') ||
1924
+ (g.uni && typeof g.uni.getSystemInfoSync === 'function')) {
1972
1925
  return 'miniprogram';
1926
+ }
1973
1927
  return 'browser';
1974
1928
  }
1975
1929
  init(options) {
@@ -2342,15 +2296,57 @@ class ClsLoggerCore {
2342
2296
  return nowTs + this.batchIntervalMs;
2343
2297
  }
2344
2298
  info(message, data = {}) {
2345
- const payload = normalizeFlatFields({ message, ...data }, 'info');
2299
+ let msg = '';
2300
+ let extra = {};
2301
+ if (message instanceof Error) {
2302
+ msg = message.message;
2303
+ extra = {
2304
+ stack: message.stack,
2305
+ name: message.name,
2306
+ ...data,
2307
+ };
2308
+ }
2309
+ else {
2310
+ msg = String(message);
2311
+ extra = data;
2312
+ }
2313
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'info');
2346
2314
  this.report({ type: 'info', data: payload, timestamp: Date.now() });
2347
2315
  }
2348
2316
  warn(message, data = {}) {
2349
- const payload = normalizeFlatFields({ message, ...data }, 'warn');
2317
+ let msg = '';
2318
+ let extra = {};
2319
+ if (message instanceof Error) {
2320
+ msg = message.message;
2321
+ extra = {
2322
+ stack: message.stack,
2323
+ name: message.name,
2324
+ ...data,
2325
+ };
2326
+ }
2327
+ else {
2328
+ msg = String(message);
2329
+ extra = data;
2330
+ }
2331
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'warn');
2350
2332
  this.report({ type: 'warn', data: payload, timestamp: Date.now() });
2351
2333
  }
2352
2334
  error(message, data = {}) {
2353
- const payload = normalizeFlatFields({ message, ...data }, 'error');
2335
+ let msg = '';
2336
+ let extra = {};
2337
+ if (message instanceof Error) {
2338
+ msg = message.message;
2339
+ extra = {
2340
+ stack: message.stack,
2341
+ name: message.name,
2342
+ ...data,
2343
+ };
2344
+ }
2345
+ else {
2346
+ msg = String(message);
2347
+ extra = data;
2348
+ }
2349
+ const payload = normalizeFlatFields({ message: msg, ...extra }, 'error');
2354
2350
  this.report({ type: 'error', data: payload, timestamp: Date.now() });
2355
2351
  }
2356
2352
  track(trackType, data = {}) {
@@ -2572,38 +2568,78 @@ class ClsLogger extends ClsLoggerCore {
2572
2568
  }
2573
2569
  }
2574
2570
  const isMini = this.envType === 'miniprogram';
2575
- // 静态字面量,方便打包器识别(但在此兼容入口里,仍然可能被一起分析)
2576
- const WEB_SDK = 'tencentcloud-cls-sdk-js-web';
2577
- const MINI_SDK = 'tencentcloud-cls-sdk-js-mini';
2578
- // UMD(浏览器脚本)优先读全局变量
2579
- if (!isMini) {
2571
+ // 3) 尝试 require / 全局变量
2572
+ // Mini Program: 尝试直接 require
2573
+ if (isMini) {
2574
+ // 显式使用字面量 require,帮助打包工具识别依赖(尤其是 CJS 构建模式下)
2575
+ try {
2576
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
2577
+ const req = typeof require === 'function' ? require('tencentcloud-cls-sdk-js-mini') : null;
2578
+ const reqSdk = normalizeSdk(req);
2579
+ if (reqSdk) {
2580
+ this.sdk = reqSdk;
2581
+ return reqSdk;
2582
+ }
2583
+ }
2584
+ catch {
2585
+ // ignore
2586
+ }
2587
+ // 尝试使用 tryRequire(作为补充)
2588
+ const reqMod = tryRequire('tencentcloud-cls-sdk-js-mini');
2589
+ const reqSdk = normalizeSdk(reqMod);
2590
+ if (reqSdk) {
2591
+ this.sdk = reqSdk;
2592
+ return reqSdk;
2593
+ }
2594
+ }
2595
+ else {
2596
+ // Web: 优先读全局变量 (UMD)
2580
2597
  const g = readGlobal('tencentcloudClsSdkJsWeb');
2581
2598
  const sdk = normalizeSdk(g);
2582
2599
  if (sdk) {
2583
2600
  this.sdk = sdk;
2584
2601
  return sdk;
2585
2602
  }
2603
+ // Web: 尝试 require
2604
+ const reqMod = tryRequire('tencentcloud-cls-sdk-js-web');
2605
+ const reqSdk = normalizeSdk(reqMod);
2606
+ if (reqSdk) {
2607
+ this.sdk = reqSdk;
2608
+ return reqSdk;
2609
+ }
2610
+ }
2611
+ // 4) 动态 import
2612
+ // 使用字符串字面量,确保 Bundler 能正确识别并进行 Code Splitting
2613
+ if (isMini) {
2614
+ this.sdkPromise = import('tencentcloud-cls-sdk-js-mini')
2615
+ .then((m) => {
2616
+ const sdk = normalizeSdk(m);
2617
+ if (!sdk)
2618
+ throw new Error(`ClsLogger.loadSdk: invalid sdk module for mini`);
2619
+ this.sdk = sdk;
2620
+ return sdk;
2621
+ })
2622
+ .catch((err) => {
2623
+ this.sdkPromise = null;
2624
+ console.error('[ClsLogger] Failed to load mini sdk:', err);
2625
+ throw err;
2626
+ });
2627
+ }
2628
+ else {
2629
+ this.sdkPromise = import('tencentcloud-cls-sdk-js-web')
2630
+ .then((m) => {
2631
+ const sdk = normalizeSdk(m);
2632
+ if (!sdk)
2633
+ throw new Error(`ClsLogger.loadSdk: invalid sdk module for web`);
2634
+ this.sdk = sdk;
2635
+ return sdk;
2636
+ })
2637
+ .catch((err) => {
2638
+ this.sdkPromise = null;
2639
+ console.error('[ClsLogger] Failed to load web sdk:', err);
2640
+ throw err;
2641
+ });
2586
2642
  }
2587
- // 尽量同步 require
2588
- const reqMod = tryRequire(isMini ? MINI_SDK : WEB_SDK);
2589
- const reqSdk = normalizeSdk(reqMod);
2590
- if (reqSdk) {
2591
- this.sdk = reqSdk;
2592
- return reqSdk;
2593
- }
2594
- // 动态 import
2595
- this.sdkPromise = (isMini ? import(MINI_SDK) : import(WEB_SDK))
2596
- .then((m) => {
2597
- const sdk = normalizeSdk(m);
2598
- if (!sdk)
2599
- throw new Error(`ClsLogger.loadSdk: invalid sdk module for ${isMini ? MINI_SDK : WEB_SDK}`);
2600
- this.sdk = sdk;
2601
- return sdk;
2602
- })
2603
- .catch((err) => {
2604
- this.sdkPromise = null;
2605
- throw err;
2606
- });
2607
2643
  return this.sdkPromise;
2608
2644
  }
2609
2645
  }