@blueking/open-telemetry 0.0.8 → 0.0.10

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,22 +1,15 @@
1
1
  # @blueking/open-telemetry
2
2
 
3
- 蓝鲸监控 RUM OT SDK,使用 OpenTelemetry 采集页面访问、接口请求、静态资源、错误、Web Vitals、设备和会话等数据,并通过 OTLP HTTP 上报。
3
+ `@blueking/open-telemetry` 是蓝鲸 RUM Web 上报 SDK。它基于 OpenTelemetry 采集页面访问、接口请求、静态资源、JS 错误、Web Vitals、白屏、设备、会话等数据,并通过 OTLP HTTP 上报到 collector。
4
4
 
5
- ## 安装和使用
5
+ ## 1. 安装和使用
6
+
7
+ ### npm 使用
6
8
 
7
9
  ```bash
8
- # npm
9
10
  npm install @blueking/open-telemetry
10
-
11
- # pnpm
12
- pnpm add @blueking/open-telemetry
13
-
14
- # yarn
15
- yarn add @blueking/open-telemetry
16
11
  ```
17
12
 
18
- ### npm 包使用
19
-
20
13
  ```javascript
21
14
  import { BkOpenTelemetry } from '@blueking/open-telemetry';
22
15
 
@@ -41,7 +34,7 @@ const bkOT = new BkOpenTelemetry({
41
34
  ```html
42
35
  <script src="https://unpkg.com/@blueking/open-telemetry/dist/bk-rum.global.js"></script>
43
36
  <script>
44
- const bkOT = new window.BkOpenTelemetry({
37
+ window.bkOT = new window.BkOpenTelemetry({
45
38
  app: {
46
39
  name: 'demo-app',
47
40
  environment: 'production',
@@ -58,46 +51,71 @@ const bkOT = new BkOpenTelemetry({
58
51
  </script>
59
52
  ```
60
53
 
61
- 默认 `autoStart: true`,所以 `new BkOpenTelemetry()` SDK 会自动启动。
54
+ `new BkOpenTelemetry()` 后默认自动启动,不需要再手动调用 `start()`。
62
55
 
63
- `transport.endpoint` 填 OTLP collector 根地址即可,SDK 会自动生成:
56
+ `transport.endpoint` 填 OTLP collector 根地址即可,SDK 会自动拼出三类上报地址:
64
57
 
65
58
  - traces: `endpoint/v1/traces`
66
59
  - metrics: `endpoint/v1/metrics`
67
60
  - logs: `endpoint/v1/logs`
68
61
 
69
- `transport.token` 会变成请求头:`Authorization: Bearer <token>`。
62
+ `transport.token` 会作为默认鉴权头发送:`Authorization: Bearer <token>`。
70
63
 
71
- ## 2. 先理解默认采集
64
+ ## 2. 默认采集
72
65
 
73
- 不写 `rum` 配置时,SDK 已经默认开启常用 RUM 能力:
66
+ 只配置 `app` `transport` 后,SDK 已经默认开启常用能力:
74
67
 
75
- - 页面加载:`documentLoad`
76
- - 页面访问:`pageView`
77
- - 接口请求:`fetch`、`xhr`
78
- - 静态资源:`resource`
79
- - JS 错误:`error`
80
- - 页面体验:`webVitals`、`blankScreen`
81
- - 用户环境:`device`、`session`
82
- - 用户交互 instrumentation:`userInteraction`
68
+ - `documentLoad`: 页面加载链路。
69
+ - `pageView`: 页面访问和 SPA 路由切换。
70
+ - `fetch`: 自动采集 fetch 接口请求。
71
+ - `xhr`: 自动采集 XMLHttpRequest 接口请求。
72
+ - `resource`: 静态资源加载耗时。
73
+ - `error`: JS 错误、Promise 异常、资源加载失败。
74
+ - `webVitals`: CLS、FCP、INP、LCP、TTFB。
75
+ - `blankScreen`: 首屏白屏检测。
76
+ - `device`: 设备、浏览器、屏幕、网络信息。
77
+ - `session`: 连续访问会话。
78
+ - `userInteraction`: OpenTelemetry 官方用户交互 instrumentation。
83
79
 
84
80
  默认关闭的能力需要手动打开:
85
81
 
86
- - `action`: 用户点击、输入、提交等操作事件
87
- - `httpBody`: 请求/响应 body 采集
88
- - `longTask`: 长任务
89
- - `routeTiming`: 路由耗时
90
- - `cspViolation`: CSP 违规
91
- - `websocket`: WebSocket 事件
82
+ - `action`: 轻量用户操作事件,支持点击、输入、提交等。
83
+ - `httpBody`: 接口异常时采集请求和响应 body
84
+ - `longTask`: 主线程 Long Task。
85
+ - `routeTiming`: SPA 路由切换耗时。
86
+ - `cspViolation`: CSP 违规事件。
87
+ - `websocket`: WebSocket 连接、消息、错误指标。
88
+
89
+ 如果要关闭默认能力,显式配置为 `false`:
90
+
91
+ ```javascript
92
+ new BkOpenTelemetry({
93
+ transport: {
94
+ endpoint: 'https://your-otlp-collector',
95
+ },
96
+ instrumentations: {
97
+ fetch: false,
98
+ xhr: false,
99
+ userInteraction: false,
100
+ },
101
+ plugins: {
102
+ webVitals: false,
103
+ blankScreen: false,
104
+ session: false,
105
+ },
106
+ });
107
+ ```
108
+
109
+ ## 3. 给数据加上应用、用户和路由
92
110
 
93
- ## 3. 给数据加上用户和路由
111
+ 建议先补齐应用标识、用户 ID 和路由归类。这样后续排查问题时,可以按应用、版本、用户、页面聚合。
94
112
 
95
113
  ```javascript
96
114
  const bkOT = new BkOpenTelemetry({
97
115
  app: {
98
- name: 'demo-app',
116
+ name: 'order-center',
99
117
  environment: 'production',
100
- version: '1.0.0',
118
+ version: '1.2.0',
101
119
  },
102
120
  transport: {
103
121
  endpoint: 'https://your-otlp-collector',
@@ -107,14 +125,23 @@ const bkOT = new BkOpenTelemetry({
107
125
  id: window.USER_ID,
108
126
  },
109
127
  route: {
110
- getPathGroup: url => new URL(url).pathname,
128
+ getPathGroup: url => {
129
+ const { pathname } = new URL(url, location.href);
130
+ return pathname.replace(/\/user\/\d+/, '/user/:id');
131
+ },
111
132
  },
112
133
  });
113
134
  ```
114
135
 
115
- `route.getPathGroup` 用来把高基数 URL 归类成低基数路径。例如 `/user/123` 可以归类成 `/user/:id`,方便聚合分析。
136
+ 常用基础配置:
137
+
138
+ - `app.name`: 应用名,会写入 `service.name`,默认 `unknown_service`。
139
+ - `app.environment`: 环境名,会写入 `deployment.environment.name`,默认 `production`。
140
+ - `app.version`: 应用版本,会写入 `service.version`。
141
+ - `user.id`: 用户 ID,会写入 `user.id`。SDK 原样透传,不做 hash 和脱敏。
142
+ - `route.getPathGroup`: 把高基数 URL 归类成低基数路由,例如 `/user/123` 归类成 `/user/:id`。
116
143
 
117
- 运行过程中也可以更新上下文:
144
+ 运行中也可以更新用户和当前 View:
118
145
 
119
146
  ```javascript
120
147
  bkOT.setUser({ id: 'user-001' });
@@ -122,85 +149,175 @@ bkOT.setUser({ id: 'user-001' });
122
149
  bkOT.setView({
123
150
  id: 'view-001',
124
151
  url: location.href,
125
- urlPathGroup: '/user/:id',
152
+ urlPathGroup: '/order/:id',
126
153
  loadingType: 'route_change',
127
154
  });
128
155
  ```
129
156
 
130
- ## 4. 按需打开更多能力
157
+ `setUser` `setView` 会更新运行期公共属性,后续 span、metric、log 都会自动带上这些字段。
158
+
159
+ ## 4. 按需打开接口、资源和路由能力
160
+
161
+ 多数 Web 应用可以从这一组配置开始:
131
162
 
132
163
  ```javascript
133
164
  new BkOpenTelemetry({
165
+ app: {
166
+ name: 'demo-app',
167
+ version: '1.0.0',
168
+ },
134
169
  transport: {
135
170
  endpoint: 'https://your-otlp-collector',
136
171
  token: 'your-report-token',
137
172
  },
138
- rum: {
139
- plugins: {
140
- action: true,
141
- longTask: { threshold: 50 },
142
- routeTiming: true,
143
- websocket: true,
144
- cspViolation: true,
145
- httpBody: {
146
- maxBodySize: 4 * 1024,
147
- redact: ({ body }) => body.replace(/password=[^&]+/g, 'password=***'),
148
- },
149
- blankScreen: {
150
- rootSelector: '#app',
151
- checkDelay: 3000,
152
- threshold: 0.8,
153
- ignoreSelectors: ['.app-loading', '.page-skeleton'],
154
- },
173
+ route: {
174
+ getPathGroup: url => new URL(url, location.href).pathname,
175
+ },
176
+ plugins: {
177
+ routeTiming: true,
178
+ longTask: { threshold: 80 },
179
+ },
180
+ });
181
+ ```
182
+
183
+ - `fetch` / `xhr`: 默认开启,采集接口耗时、状态码、请求方法、URL 归类等。
184
+ - `resource`: 默认开启,采集 img、script、css 等静态资源耗时、大小、缓存命中和协议。
185
+ - `pageView`: 默认开启,监听 `pushState`、`replaceState`、`popstate`、`hashchange`。
186
+ - `routeTiming`: 默认关闭,估算 SPA 路由切换到下一帧渲染完成的耗时。
187
+ - `longTask`: 默认关闭,采集主线程长任务。`threshold` 默认 `50` ms。
188
+
189
+ SDK 会自动忽略指向自身 OTLP 上报地址的请求,避免上报请求被再次采集导致循环放大。
190
+
191
+ ## 5. 配置错误、白屏和 CSP
192
+
193
+ ```javascript
194
+ new BkOpenTelemetry({
195
+ transport: {
196
+ endpoint: 'https://your-otlp-collector',
197
+ },
198
+ plugins: {
199
+ error: {
200
+ windowMs: 60 * 1000,
201
+ maxPerWindow: 5,
155
202
  },
203
+ blankScreen: {
204
+ rootSelector: '#app',
205
+ checkDelay: 3000,
206
+ threshold: 0.8,
207
+ ignoreSelectors: ['.app-loading', '.page-skeleton'],
208
+ },
209
+ cspViolation: true,
156
210
  },
157
211
  });
158
212
  ```
159
213
 
160
- 如果要关闭默认能力,显式写 `false`:
214
+ 错误采集说明:
215
+
216
+ - `error`: 默认开启,采集 `window.error`、`unhandledrejection`、资源加载失败。
217
+ - `error.windowMs`: 同类错误节流窗口,默认 `60000` ms。
218
+ - `error.maxPerWindow`: 同类错误在窗口内最多上报条数,默认 `5`。
219
+ - `cspViolation`: 默认关闭,监听 `securitypolicyviolation` 事件。适合有 CSP 策略的站点开启。
220
+
221
+ 白屏检测说明:
222
+
223
+ - `blankScreen`: 默认开启,只在判定为白屏时上报。
224
+ - `blankScreen.rootSelector`: 应用挂载点。Vue / React 项目建议配置为 `#app` 或 `#root`。
225
+ - `blankScreen.checkDelay`: DOM ready 后延迟多久检测,默认 `3000` ms。
226
+ - `blankScreen.threshold`: 空白采样点比例阈值,范围 `0 - 1`,默认 `0.8`。
227
+ - `blankScreen.ignoreSelectors`: 追加 loading、骨架屏等忽略选择器,命中后不计入空白比例。
228
+
229
+ ## 6. 配置用户操作和 WebSocket
161
230
 
162
231
  ```javascript
163
232
  new BkOpenTelemetry({
164
233
  transport: {
165
234
  endpoint: 'https://your-otlp-collector',
166
- token: 'your-report-token',
167
235
  },
168
- rum: {
169
- plugins: {
170
- webVitals: false,
171
- blankScreen: false,
236
+ plugins: {
237
+ action: {
238
+ eventNames: ['click', 'submit', 'keydown'],
172
239
  },
173
- instrumentations: {
174
- fetch: false,
175
- xhr: false,
240
+ websocket: true,
241
+ },
242
+ });
243
+ ```
244
+
245
+ `action` 用于上报轻量用户操作:
246
+
247
+ - `action: true`: 采集 `click`、`submit`、`keydown`。
248
+ - `action.eventNames`: 自定义采集事件,支持 `click`、`input`、`keydown`、`pointerdown`、`scroll`、`submit`。
249
+ - 上报时会截取元素文本、标签名,并写入 `action.type`、`target.text_short`、`target.tag`。
250
+
251
+ `websocket` 用于采集 WebSocket:
252
+
253
+ - 连接成功耗时:`browser.websocket.connect.duration`。
254
+ - 收发消息数:`browser.websocket.message.count`。
255
+ - 收发字节数:`browser.websocket.message.bytes`。
256
+ - 错误数:`browser.websocket.error.count`。
257
+
258
+ SDK 会忽略指向自身上报地址的 WebSocket URL。
259
+
260
+ ## 7. 采集异常接口 body
261
+
262
+ `httpBody` 默认关闭。它会 patch `fetch` 和 `XMLHttpRequest`,只在请求失败、请求抛错或状态码 `>= 400` 时上报 body。
263
+
264
+ ```javascript
265
+ new BkOpenTelemetry({
266
+ transport: {
267
+ endpoint: 'https://your-otlp-collector',
268
+ },
269
+ plugins: {
270
+ httpBody: {
271
+ maxBodySize: 4 * 1024,
272
+ redact: ({ body, type, url, status, truncated }) => {
273
+ return body.replace(/password=[^&]+/g, 'password=***').replace(/token=[^&]+/g, 'token=***');
274
+ },
176
275
  },
177
276
  },
178
277
  });
179
278
  ```
180
279
 
181
- ## 5. 加公共属性和脱敏
280
+ 配置项:
281
+
282
+ - `httpBody: true`: 使用默认配置开启。
283
+ - `httpBody.maxBodySize`: 单个请求或响应 body 最大采集长度,默认 `10 * 1024` 字符。
284
+ - `httpBody.redact`: body 上报前的脱敏函数,必须返回字符串。
182
285
 
183
- 公共属性适合放业务线、页面、环境等每条数据都想带上的信息。
286
+ `redact` 入参:
287
+
288
+ - `body`: 已截断后的 body 字符串。
289
+ - `type`: `request` 或 `response`。
290
+ - `url`: 请求 URL。
291
+ - `method`: 请求方法。
292
+ - `status`: 响应状态码,网络错误时可能为空。
293
+ - `contentType`: body 的 content-type。
294
+ - `truncated`: 是否被 `maxBodySize` 截断。
295
+
296
+ 建议只在排障需要时开启 `httpBody`,并务必处理密码、token、手机号等敏感信息。
297
+
298
+ ## 8. 加公共属性和脱敏
299
+
300
+ 公共属性适合放业务线、模块、页面类型等每条数据都想带上的信息。
184
301
 
185
302
  ```javascript
186
303
  new BkOpenTelemetry({
187
304
  transport: {
188
305
  endpoint: 'https://your-otlp-collector',
189
- token: 'your-report-token',
190
306
  },
191
307
  attributes: {
192
308
  page: () => ({
309
+ 'biz.module': 'order',
193
310
  'rum.page.host': location.host,
194
311
  'rum.page.path': location.pathname,
195
312
  }),
196
- custom: () => ({
197
- 'biz.team': 'demo',
313
+ metric: () => ({
314
+ 'biz.metric_source': 'rum',
198
315
  }),
199
316
  error: () => ({
200
317
  'biz.error_source': 'browser',
201
318
  }),
202
- metric: () => ({
203
- 'biz.metric_source': 'rum',
319
+ custom: () => ({
320
+ 'biz.team': 'demo',
204
321
  }),
205
322
  },
206
323
  privacy: {
@@ -218,77 +335,152 @@ new BkOpenTelemetry({
218
335
  });
219
336
  ```
220
337
 
221
- - `attributes.page`: 页面、接口、资源等 RUM 数据都会带上。
338
+ `attributes` 配置项:
339
+
340
+ - `attributes.page`: 页面、接口、资源、错误等 RUM 数据都会带上。
341
+ - `attributes.metric`: Web Vitals、Long Task、Route Timing、WebSocket 等 metric 会带上。
342
+ - `attributes.error`: JS 错误、白屏、CSP 等错误类数据会带上。
222
343
  - `attributes.custom`: `reportCustomEvent` 上报的自定义事件会带上。
223
- - `attributes.error`: 错误数据会带上。
224
- - `attributes.metric`: 指标数据会带上。
225
- - `privacy.redactUrl`: 处理 URL,例如 `url.full`、`document.referrer`。
226
- - `privacy.redactAttributes`: 处理 span/log 属性。
227
- - `rum.plugins.httpBody.redact`: 只处理请求/响应 body。
228
344
 
229
- ## 6. 手动上报业务事件
345
+ `privacy` 配置项:
346
+
347
+ - `privacy.redactUrl`: 处理 URL,例如 `url.full`、`document.referrer`、资源 URL。
348
+ - `privacy.redactAttributes`: 处理 span 和 log 属性。适合兜底清理敏感字段。
349
+ - `plugins.httpBody.redact`: 只处理请求和响应 body。
350
+
351
+ 脱敏顺序可以简单理解为:URL 先走 `redactUrl`,属性整体再走 `redactAttributes`。
352
+
353
+ ## 9. 配置设备和会话
354
+
355
+ `device` 和 `session` 默认开启,一般不需要配置。多应用共用同一域名时,可以自定义 storage key。
356
+
357
+ ```javascript
358
+ new BkOpenTelemetry({
359
+ transport: {
360
+ endpoint: 'https://your-otlp-collector',
361
+ },
362
+ plugins: {
363
+ device: {
364
+ storageKey: 'DEMO_DEVICE_ID',
365
+ },
366
+ session: {
367
+ storageKey: 'DEMO_SESSION',
368
+ inactivityMs: 30 * 60 * 1000,
369
+ maxLifetimeMs: 24 * 60 * 60 * 1000,
370
+ },
371
+ },
372
+ });
373
+ ```
374
+
375
+ `device` 配置项:
376
+
377
+ - `device: true`: 使用默认设备配置。
378
+ - `device.storageKey`: 设备 ID 的 localStorage key,默认 `BK_RUM_DEVICE_ID`。
379
+ - 设备 ID 跨会话持久,会写入 `device.id`。
380
+
381
+ `session` 配置项:
382
+
383
+ - `session: true`: 使用默认会话配置。
384
+ - `session.storageKey`: 会话 storage key。默认会按上报 endpoint host 自动生成隔离后缀。
385
+ - `session.inactivityMs`: 用户不活跃多久后创建新会话,默认 `30` 分钟。
386
+ - `session.maxLifetimeMs`: 会话最长持续时间,默认 `24` 小时。
387
+
388
+ 会话会写入 `session.id`,并在首次创建或轮换时上报 `session.start` / `session.rotate` log。
389
+
390
+ ## 10. 手动上报业务事件
391
+
392
+ ### 自定义事件
230
393
 
231
394
  ```javascript
232
395
  bkOT.reportCustomEvent({
233
396
  name: 'order.checkout',
234
397
  attributes: {
235
- 'biz.order_id': 'O20260509001',
398
+ 'biz.order_id': 'O20260527001',
236
399
  'biz.order_amount': 199,
237
400
  },
238
401
  });
239
402
  ```
240
403
 
241
- 失败事件可以带 `error`:
404
+ ### 自定义失败事件
242
405
 
243
406
  ```javascript
244
407
  bkOT.reportCustomEvent({
245
408
  name: 'order.checkout',
246
409
  attributes: {
247
- 'biz.order_id': 'O20260509001',
410
+ 'biz.order_id': 'O20260527001',
248
411
  },
249
412
  error: new Error('库存不足'),
250
413
  });
251
414
  ```
252
415
 
253
- 也可以手动上报用户操作:
416
+ ### 手动上报用户操作
254
417
 
255
418
  ```javascript
256
419
  bkOT.reportAction({
257
420
  type: 'click',
258
421
  targetText: '立即购买',
259
422
  targetTag: 'button',
423
+ attributes: {
424
+ 'biz.order_id': 'O20260527001',
425
+ },
260
426
  });
261
427
  ```
262
428
 
263
- ## 7. 控制采样、调试和上报
429
+ 说明:
430
+
431
+ - `reportCustomEvent.name`: 事件名,会生成 `custom.${name}` span。
432
+ - `reportCustomEvent.attributes`: 业务属性,会和 `attributes.custom` 合并。
433
+ - `reportCustomEvent.error`: 传入后事件结果会标记为 error,并记录 exception。
434
+ - `reportAction.type`: 操作类型,会生成 `action.${type}` span。
435
+ - 未命中采样时,手动上报事件会被静默丢弃;`debug: true` 时会打印提示。
436
+
437
+ ## 11. 控制采样、调试和上报
264
438
 
265
439
  ```javascript
266
440
  new BkOpenTelemetry({
267
441
  debug: true,
442
+ enabled: true,
268
443
  sampling: {
269
444
  rate: 0.2,
270
445
  },
271
446
  spanProcessor: 'batch',
447
+ spanBatch: {
448
+ maxQueueSize: 2048,
449
+ maxExportBatchSize: 512,
450
+ scheduledDelayMillis: 5000,
451
+ exportTimeoutMillis: 30000,
452
+ },
272
453
  transport: {
273
454
  endpoint: 'https://your-otlp-collector',
274
455
  token: 'your-report-token',
275
456
  headers: {
276
- 'X-Custom-Header': 'value',
457
+ 'X-Biz-ID': 'demo',
277
458
  },
278
459
  signals: {
279
460
  traces: {
280
461
  timeoutMillis: 10000,
281
462
  },
463
+ metrics: {
464
+ concurrencyLimit: 2,
465
+ },
282
466
  },
283
467
  },
284
468
  });
285
469
  ```
286
470
 
287
- - `debug`: 打开后会在控制台输出调试信息。
471
+ 常用控制项:
472
+
473
+ - `enabled`: 是否启用 SDK,默认 `true`。设为 `false` 后不会启动采集和上报。
474
+ - `debug`: 是否在控制台输出 exporter 数据和插件异常,默认 `false`。
288
475
  - `sampling.rate`: 采样率,范围 `0 - 1`,默认 `1`。
289
- - `spanProcessor`: 默认 `batch`;本地调试可用 `simple`。
290
- - `transport.headers`: 给所有信号加请求头。
291
- - `transport.signals.traces/metrics/logs`: 分别配置不同信号。
476
+ - `spanProcessor`: trace processor 模式,默认 `batch`。本地调试可用 `simple`。
477
+ - `spanBatch`: `batch` 模式的批量上报配置。
478
+ - `transport.endpoint`: OTLP collector 根地址,默认 `http://localhost:4318`。
479
+ - `transport.token`: 默认鉴权 token。
480
+ - `transport.headers`: 所有信号共用请求头。
481
+ - `transport.signals.traces/metrics/logs`: 分别配置某一类信号。
482
+
483
+ 采样结果会在一次浏览器会话中保持稳定。`rate < 1` 时,SDK 会把采样结果写入 `sessionStorage`;不可用时降级到内存缓存。
292
484
 
293
485
  如果三类信号要发到不同地址:
294
486
 
@@ -299,44 +491,46 @@ new BkOpenTelemetry({
299
491
  token: 'your-report-token',
300
492
  signals: {
301
493
  endpoints: {
302
- traces: 'https://your-trace-collector/v1/traces',
303
- metrics: 'https://your-metric-collector/v1/metrics',
304
- logs: 'https://your-log-collector/v1/logs',
494
+ traces: 'https://trace.example.com/v1/traces',
495
+ metrics: 'https://metric.example.com/v1/metrics',
496
+ logs: 'https://log.example.com/v1/logs',
305
497
  },
306
498
  },
307
499
  },
308
500
  });
309
501
  ```
310
502
 
311
- 请求头优先级为:`token` 默认头 < `transport.headers` < 单信号 `headers`。
503
+ 请求头优先级为:`transport.token` 默认头 < `transport.headers` < 单信号 `headers`。
312
504
 
313
- ## 8. 生命周期
505
+ ## 12. 控制启动和生命周期
314
506
 
315
- ```javascript
316
- await bkOT.flush();
317
- await bkOT.shutdown();
318
- ```
319
-
320
- - `flush`: 立即刷新插件、trace、metric、log。
321
- - `shutdown`: 刷新后关闭 SDK,并卸载事件监听。
322
-
323
- 如果你要先注册插件,再手动启动:
507
+ 默认 `autoStart: true`。如果要先注册自定义插件或 instrumentation,再启动 SDK,可以关闭自动启动。
324
508
 
325
509
  ```javascript
326
510
  const bkOT = new BkOpenTelemetry({
327
511
  autoStart: false,
328
512
  transport: {
329
513
  endpoint: 'https://your-otlp-collector',
330
- token: 'your-report-token',
331
514
  },
332
515
  });
333
516
 
334
517
  await bkOT.start();
335
518
  ```
336
519
 
337
- ## 9. 扩展插件
520
+ 生命周期方法:
521
+
522
+ ```javascript
523
+ await bkOT.flush();
524
+ await bkOT.shutdown();
525
+ ```
526
+
527
+ - `start`: 启动 provider、instrumentation 和插件。重复调用会直接返回。
528
+ - `flush`: 立即刷新插件、trace、metric、log。
529
+ - `shutdown`: 先刷新,再卸载插件、事件监听和 instrumentation。关闭后不能再次启动同一个实例。
530
+
531
+ ## 13. 扩展插件
338
532
 
339
- 普通用户通常不需要看这一节。只有当默认采集不够用时,再使用插件扩展。
533
+ 普通接入方通常不需要扩展插件。只有默认采集不满足时,再使用插件能力。
340
534
 
341
535
  ```javascript
342
536
  import { BkOpenTelemetry, createPlugin } from '@blueking/open-telemetry';
@@ -348,17 +542,20 @@ const plugin = createPlugin({
348
542
  'biz.plugin_enabled': true,
349
543
  });
350
544
 
351
- const span = context.startSpan('demo.plugin_ready');
545
+ const span = context.startSpan('demo.plugin_ready', {
546
+ 'biz.plugin': 'demo',
547
+ });
352
548
  span.end();
353
549
  },
354
550
  });
355
551
 
356
552
  const bkOT = new BkOpenTelemetry({
357
553
  autoStart: false,
358
- plugins: [plugin],
554
+ plugins: {
555
+ custom: [plugin],
556
+ },
359
557
  transport: {
360
558
  endpoint: 'https://your-otlp-collector',
361
- token: 'your-report-token',
362
559
  },
363
560
  });
364
561
 
@@ -371,7 +568,17 @@ await bkOT.start();
371
568
  bkOT.use(plugin);
372
569
  ```
373
570
 
374
- ## 10. 接入原生 OpenTelemetry Instrumentation
571
+ 插件上下文常用方法:
572
+
573
+ - `context.startSpan`: 创建 span。
574
+ - `context.emitLog`: 上报 log,并自动带上运行期公共属性和脱敏。
575
+ - `context.meter`: 创建 metric。
576
+ - `context.setRuntimeAttributes`: 更新后续数据都会携带的公共属性。
577
+ - `context.getRuntimeAttributes`: 获取当前公共属性快照。
578
+ - `context.setUser`: 更新用户上下文。
579
+ - `context.setView`: 更新 View 上下文。
580
+
581
+ ## 14. 接入原生 OpenTelemetry Instrumentation
375
582
 
376
583
  ```javascript
377
584
  import { BkOpenTelemetry } from '@blueking/open-telemetry';
@@ -379,10 +586,11 @@ import { MyCustomInstrumentation } from './my-custom-instrumentation';
379
586
 
380
587
  const bkOT = new BkOpenTelemetry({
381
588
  autoStart: false,
382
- instrumentations: [new MyCustomInstrumentation()],
589
+ instrumentations: {
590
+ custom: [new MyCustomInstrumentation()],
591
+ },
383
592
  transport: {
384
593
  endpoint: 'https://your-otlp-collector',
385
- token: 'your-report-token',
386
594
  },
387
595
  });
388
596
 
@@ -394,3 +602,107 @@ await bkOT.start();
394
602
  ```javascript
395
603
  bkOT.useInstrumentation(new MyCustomInstrumentation());
396
604
  ```
605
+
606
+ 注意:`use` 和 `useInstrumentation` 必须在 `start()` 前调用。如果使用默认自动启动,请改成 `autoStart: false`。
607
+
608
+ ## 15. 完整配置速查
609
+
610
+ ```javascript
611
+ new BkOpenTelemetry({
612
+ app: {
613
+ name: 'demo-app',
614
+ environment: 'production',
615
+ version: '1.0.0',
616
+ },
617
+ user: {
618
+ id: 'user-001',
619
+ },
620
+ transport: {
621
+ endpoint: 'https://your-otlp-collector',
622
+ token: 'your-report-token',
623
+ headers: {},
624
+ signals: {
625
+ endpoints: {
626
+ traces: 'https://your-otlp-collector/v1/traces',
627
+ metrics: 'https://your-otlp-collector/v1/metrics',
628
+ logs: 'https://your-otlp-collector/v1/logs',
629
+ },
630
+ traces: {
631
+ headers: {},
632
+ timeoutMillis: 10000,
633
+ concurrencyLimit: 2,
634
+ },
635
+ metrics: {},
636
+ logs: {},
637
+ },
638
+ },
639
+ enabled: true,
640
+ autoStart: true,
641
+ debug: false,
642
+ sampling: {
643
+ rate: 1,
644
+ },
645
+ spanProcessor: 'batch',
646
+ spanBatch: {
647
+ maxQueueSize: 2048,
648
+ maxExportBatchSize: 512,
649
+ scheduledDelayMillis: 5000,
650
+ exportTimeoutMillis: 30000,
651
+ },
652
+ route: {
653
+ getPathGroup: url => new URL(url, location.href).pathname,
654
+ },
655
+ attributes: {
656
+ page: () => ({}),
657
+ metric: () => ({}),
658
+ error: () => ({}),
659
+ custom: () => ({}),
660
+ },
661
+ privacy: {
662
+ redactUrl: url => url,
663
+ redactAttributes: attributes => attributes,
664
+ },
665
+ instrumentations: {
666
+ documentLoad: true,
667
+ fetch: true,
668
+ xhr: true,
669
+ userInteraction: true,
670
+ },
671
+ plugins: {
672
+ pageView: true,
673
+ resource: true,
674
+ error: true,
675
+ webVitals: true,
676
+ blankScreen: true,
677
+ device: true,
678
+ session: true,
679
+ action: false,
680
+ httpBody: false,
681
+ longTask: false,
682
+ routeTiming: false,
683
+ cspViolation: false,
684
+ websocket: false,
685
+ },
686
+ });
687
+ ```
688
+
689
+ 配置默认值:
690
+
691
+ - `autoStart`: 默认 `true`。
692
+ - `enabled`: 默认 `true`。
693
+ - `debug`: 默认 `false`。
694
+ - `sampling.rate`: 默认 `1`。
695
+ - `spanProcessor`: 默认 `batch`。
696
+ - `transport.endpoint`: 默认 `http://localhost:4318`。
697
+ - `app.environment`: 默认 `production`。
698
+ - `app.name`: 默认 `unknown_service`。
699
+
700
+ ## 16. 推荐接入顺序
701
+
702
+ 新项目建议按下面顺序接入:
703
+
704
+ 1. 先配置 `app`、`transport`、`user`,确认页面访问、错误、接口请求能上报。
705
+ 2. 再配置 `route.getPathGroup`,避免 URL 动态 ID 导致维度过高。
706
+ 3. 按业务需要开启 `routeTiming`、`longTask`、`action`、`websocket`。
707
+ 4. 排障时再开启 `httpBody`,并先做好脱敏。
708
+ 5. 最后补充 `attributes` 和 `privacy`,统一业务维度和敏感信息处理。