npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

chinalife-otel-web-sdk

v1.0.0

Published

OpenTelemetry Web SDK - Simplified wrapper for frontend applications

Readme

@chinalife/otel-web-sdk

OpenTelemetry Web SDK - 简化的前端追踪 SDK,封装 OpenTelemetry JS API,提供简单易用的接口。

特性

  • 简单易用 - 一行代码完成初始化
  • 自动追踪 - 自动 instrument HTTP 请求、路由跳转等
  • 多框架支持 - 支持 Vue、React、H5 应用
  • 环境变量配置 - 支持通过环境变量配置,无需修改代码
  • TypeScript 支持 - 完整的 TypeScript 类型定义
  • CDN 支持 - 支持通过 CDN 方式引入

安装

npm install @chinalife/otel-web-sdk
# 或
yarn add @chinalife/otel-web-sdk

快速开始

最简配置

import { initOTel } from '@chinalife/otel-web-sdk';

// 一键初始化,使用环境变量或默认配置
initOTel();

完整配置

import { initOTel } from '@chinalife/otel-web-sdk';

initOTel({
  serviceName: 'frontend-vue-app',
  serviceVersion: '1.0.0',
  environment: 'production',
  datacenter: 'dc1',
  collectorEndpoint: 'http://collector-dc1.otel.svc.cluster.local:4318/v1/traces',
  samplingRatio: 1.0, // 100%采样(默认)
  enableAutoInstrumentation: true,
  enableRouterTracing: true,
  enableHttpTracing: true,
  propagationFormat: 'w3c', // 传播协议格式:'w3c' | 'b3multi' | 'pinpoint' | ['w3c', 'b3multi']
});

Vue 应用集成

// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { initOTel } from '@chinalife/otel-web-sdk';

// 在应用启动前初始化 SDK
initOTel({
  serviceName: 'frontend-vue-app',
  framework: 'vue',
  router: router, // 自动 instrument 路由
  collectorEndpoint: process.env.VITE_OTEL_COLLECTOR_ENDPOINT || 
    'http://collector-dc1.otel.svc.cluster.local:4318/v1/traces',
});

const app = createApp(App);
app.use(router);
app.mount('#app');

React 应用集成

// index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { initOTel } from '@chinalife/otel-web-sdk';

// 初始化 SDK
initOTel({
  serviceName: 'frontend-react-app',
  framework: 'react',
  collectorEndpoint: process.env.REACT_APP_OTEL_COLLECTOR_ENDPOINT || 
    'http://collector-dc1.otel.svc.cluster.local:4318/v1/traces',
});

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

H5 应用集成

CDN 方式

<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/@chinalife/otel-web-sdk@latest/dist/index.umd.js"></script>
</head>
<body>
  <script>
    // 初始化 SDK
    window.OTelSDK.init({
      serviceName: 'h5-app',
      collectorEndpoint: 'http://collector-dc1.otel.svc.cluster.local:4318/v1/traces',
      samplingRatio: 1.0,
    });
  </script>
</body>
</html>

手动创建 Span

import { trace } from '@chinalife/otel-web-sdk';

// 方式1: 手动管理 span
function handleUserAction() {
  const span = trace.startSpan('user_action', {
    attributes: {
      'action.type': 'button_click',
      'action.name': 'submit_form',
    },
  });
  
  try {
    await submitForm();
    span.setStatus({ code: 1 }); // 1 = OK
  } catch (error: any) {
    span.setStatus({ code: 2, message: error.message }); // 2 = ERROR
    span.recordException(error);
    throw error;
  } finally {
    span.end();
  }
}

// 方式2: 使用 withSpan(自动管理)
async function handleUserAction() {
  await trace.withSpanAsync('user_action', async (span) => {
    span.setAttributes({
      'action.type': 'button_click',
      'action.name': 'submit_form',
    });
    await submitForm();
  });
}

// 方式3: 同步函数
function processData() {
  return trace.withSpan('process_data', (span) => {
    span.setAttributes({ 'data.size': data.length });
    return process(data);
  });
}

获取 Trace 信息

import { trace } from '@chinalife/otel-web-sdk';

// 获取当前 Trace ID
const traceId = trace.getCurrentTraceId();
console.log('Current Trace ID:', traceId);

// 获取当前 Span ID
const spanId = trace.getCurrentSpanId();
console.log('Current Span ID:', spanId);

// 获取当前活动的 Span
const activeSpan = trace.getActiveSpan();
if (activeSpan) {
  activeSpan.setAttribute('custom.key', 'value');
}

传播协议配置

SDK 支持多种 Trace 传播协议格式,用于在不同系统间传递 Trace 上下文信息。

支持的传播协议

  • W3C Trace Context (w3c) - W3C 标准,使用 traceparenttracestate 头部(默认)
  • B3 Multi (b3multi) - Zipkin B3 多头部格式,使用 X-B3-TraceIdX-B3-SpanId
  • B3 Single (b3) - Zipkin B3 单头部格式
  • Pinpoint (pinpoint) - Naver Pinpoint 格式,使用 Pinpoint-TraceIdPinpoint-SpanId

使用单个传播协议

import { initOTel } from '@chinalife/otel-web-sdk';

// 使用 W3C Trace Context(默认)
initOTel({
  serviceName: 'my-app',
  propagationFormat: 'w3c',
});

// 使用 B3 Multi
initOTel({
  serviceName: 'my-app',
  propagationFormat: 'b3multi',
});

// 使用 Pinpoint
initOTel({
  serviceName: 'my-app',
  propagationFormat: 'pinpoint',
});

同时使用多个传播协议

当需要同时支持多种后端系统时,可以配置多个传播协议:

initOTel({
  serviceName: 'my-app',
  // 同时使用 W3C 和 B3,HTTP 请求会同时携带两种格式的头部
  propagationFormat: ['w3c', 'b3multi'],
});

通过环境变量配置

# .env 文件
# 单个协议
OTEL_PROPAGATION_FORMAT=w3c

# 或多个协议(逗号分隔)
OTEL_PROPAGATION_FORMAT=w3c,b3multi

# 或使用 Vite 环境变量
VITE_OTEL_PROPAGATION_FORMAT=pinpoint

传播协议头部说明

W3C Trace Context:

  • traceparent: 00-<trace-id>-<parent-id>-<flags>
  • tracestate: 可选的键值对列表

B3 Multi:

  • X-B3-TraceId: 128 位或 64 位 trace ID
  • X-B3-SpanId: 64 位 span ID
  • X-B3-ParentSpanId: 64 位父 span ID(可选)
  • X-B3-Sampled: 10
  • X-B3-Flags: 调试标志(可选)

Pinpoint:

  • Pinpoint-TraceId: 16 字节十六进制 trace ID
  • Pinpoint-SpanId: 8 字节十六进制 span ID
  • Pinpoint-ParentSpanId: 8 字节十六进制父 span ID(可选)
  • Pinpoint-Sampled: 10
  • Pinpoint-Flags: 标志位(通常为 0

环境变量配置

支持通过环境变量配置,无需修改代码:

# .env 文件
OTEL_EXPORTER_OTLP_ENDPOINT=http://collector-dc1.otel.svc.cluster.local:4318/v1/traces
OTEL_SERVICE_NAME=frontend-vue-app
OTEL_SERVICE_VERSION=1.0.0
OTEL_SAMPLING_RATIO=1.0
OTEL_DEPLOYMENT_ENVIRONMENT=production
OTEL_DATACENTER=dc1
OTEL_LOG_LEVEL=info

API 参考

initOTel(options?: SDKOptions)

初始化 SDK。

参数:

  • options.serviceName - 服务名称
  • options.serviceVersion - 服务版本
  • options.environment - 环境(development/production)
  • options.datacenter - 数据中心(dc1/dc2/dc3)
  • options.collectorEndpoint - Collector 端点
  • options.samplingRatio - 采样率(0-1,默认1.0)
  • options.enableAutoInstrumentation - 启用自动 instrumentation
  • options.enableRouterTracing - 启用路由追踪
  • options.enableHttpTracing - 启用 HTTP 追踪
  • options.framework - 框架类型(vue/react/h5)
  • options.router - Vue Router 实例(Vue 专用)
  • options.propagationFormat - 传播协议格式('w3c' | 'b3multi' | 'b3' | 'pinpoint' | string[]),默认 'w3c'

trace.startSpan(name, options?)

创建并启动一个 span。

trace.withSpan(name, fn, options?)

在上下文中执行函数并创建 span(同步)。

trace.withSpanAsync(name, fn, options?)

在上下文中执行函数并创建 span(异步)。

trace.getCurrentTraceId()

获取当前 Trace ID。

trace.getCurrentSpanId()

获取当前 Span ID。

trace.getActiveSpan()

获取当前活动的 Span。

开发

# 安装依赖
npm install

# 构建
npm run build

# 开发模式(监听文件变化)
npm run dev

许可证

MIT