# @grafana/faro-react-native-tracing 中文文档

规范地址：https://npmcn.com/package/%40grafana/faro-react-native-tracing/

版本：2\.0\.4
npm 元数据更新时间：2026-10-28T13:01:02.811Z
中文译文更新时间：2026-11-16T21:59:33.288Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40grafana/faro-react-native-tracing
原文对照：https://npmcn.com/package/%40grafana/faro-react-native-tracing/?lang=original
项目主页：https://github.com/grafana/faro-react-native-sdk
源码仓库：https://github.com/grafana/faro-react-native-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：423 kB，84 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：12 个
- peer 依赖：react-native \>=0\.70\.0
- 首次发布：2026-03-30T16:09:39.151Z
- 最新版本发布：2026-10-28T13:01:02.203Z
- 近 30 天下载量：15676（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：12（近 12 个月 12 个）

## 中文简介

Faro React Industrial tracking explocation with OpenTeleometry. 法罗反应原生追踪与OpenTeleometry的实现.

## 安装

```sh
npm install @grafana/faro-react-native-tracing
```

也可以使用：`pnpm add @grafana/faro-react-native-tracing`、`yarn add @grafana/faro-react-native-tracing`、`bun add @grafana/faro-react-native-tracing`

## README

# @grafana/faro-resact-native-tracting (英语)

OpenTeleometry分布式跟踪集成法罗反应原生SDK.

## 安装

```bash
npm install @grafana/faro-react-native-tracing
# or
yarn add @grafana/faro-react-native-tracing
```

**先决条件:**

-   `@grafana/faro-react-native` - 反应原生核心法罗SDK
-   0.70或以上反应

## 快速启动

启用通过 `enableTracing` 旗帜 - 不需要添加 `TracingInstrumentation` 改为 `instrumentations`数字 :

```typescript
import { initializeFaro } from '@grafana/faro-react-native';

const faro = initializeFaro({
  url: 'https://faro-collector-prod-YOUR-REGION.grafana.net/collect/YOUR_TOKEN_HERE',
  app: {
    name: 'my-react-native-app',
    version: '1.0.0',
    environment: 'production',
  },
  enableTracing: true,
  tracingOptions: {
    // Optional: Propagate trace headers to these URLs for distributed tracing
    instrumentationOptions: {
      propagateTraceHeaderCorsUrls: [/https:\/\/my-api\.com/],
    },
  },
});
```

就这样! 通过 HTTP 请求 `fetch()` 现在自动追踪(并在启用用户动作跟踪时与用户动作相关)并发送给您的法罗收藏器.

## HTTP 跨度和活动公约

使用 OpenTeleometry 的内置获取跟踪 [稳定的HTTP公约](https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name), (中文(简体) ), 带有诸如 `GET` 财务报告和审定财务报表 `POST`属性包括: `http.request.method`, (中文(简体) ), `url.full`, (中文(简体) ), `server.address`, (中文(简体) ), `server.port`,以及 `http.response.status_code`。 。 。 . 成功反应请假情况 UNSET;普通4xx/5xxx答复设置错误反应 和字符串 `error.type`。没有获取会话模式设置.

这个 `faro.tracing.fetch` 事件保存 `http.method`, (中文(简体) ), `http.url`, (中文(简体) ), `http.status_code`, (中文(简体) ), `http.host`,以及 `http.scheme`。事件属性,包括 `duration_ns`,为 字符串。 活动保留会话和跟踪/扩展上下文并使用共享活动 用于分解和运输钩的管道。 可选 XHR 追踪和习俗 文书使用自己的公约.

获取跨度在请求开始时抓取当前用户动作 。 延迟获取 事件仍然可以通过事件缓冲与后期动作相接.

## 在本地反应中获取 vs XHR

默认情况下, 此软件包会跟踪 `fetch()` 只有请求.

执行原生工具 `fetch()` 顶上 `XMLHttpRequest`如果为同一 URL 启用了获取和 XHR 仪器,则一个逻辑 `fetch()` 请求可以产生两个跨度: 从 `FetchInstrumentation` 一个来自底部的XHR层。 为避免重复HTTP遥测,XHR追踪默认被禁用.

如果你的应用使用轴或直接 `XMLHttpRequest` 电话代替 `fetch()`,使XHR能够明确追踪:

```typescript
initializeFaro({
  enableTracing: true,
  tracingOptions: {
    instrumentationOptions: {
      enableXhrInstrumentation: true,
    },
  },
});
```

如果你的应用程序同时使用 `fetch()` 并避免两次追查同一请求。 或只追踪一个 API 表面:

```typescript
initializeFaro({
  enableTracing: true,
  tracingOptions: {
    instrumentationOptions: {
      // Useful for axios/direct XHR apps.
      enableFetchInstrumentation: false,
      enableXhrInstrumentation: true,
    },
  },
});
```

或既允许又允许使用 `ignoreUrls` 在一个仪器上,所以 URL 模式不会重叠 :

```typescript
initializeFaro({
  enableTracing: true,
  tracingOptions: {
    instrumentationOptions: {
      enableXhrInstrumentation: true,
      xhrInstrumentationOptions: {
        // Example: fetch() handles your API calls, so ignore those URLs in XHR.
        ignoreUrls: [/\/api\//],
      },
    },
  },
});
```

## 特征

### 🚀 **自动跟踪**

-   **获取仪器**数字 : `fetch()` 请求会被自动跟踪, 没有代码更改
-   **可选 XHR 仪器**: 启用轴或直线 `XMLHttpRequest` 电话
-   **会话关联**: 追踪与法罗会话相关, 用于完整的用户行程跟踪
-   **用户动作关联**: Tracks与 Faro 用户动作相关(当启用用户动作跟踪时)
-   **用户背景**: 用户信息自动添加以覆盖属性
-   **设备元数据**: 包含在痕迹中的设备和平台信息(device模型,OS,locale等)

### 🔗 **分布式追踪**

-   **W3C 追踪上下文**: 通过HTTP头进行符合标准的痕量传播
-   **背景宣传**: 无缝连接前端跟踪到后端服务
-   **可配置的 CORS**: 控制 API 接收微量头

### 🎯 **手动扩展创建**

-   **OTEL API 访问**: 完整的 OpenTelection API 通过 `faro.otel`
-   **自定义纸**: 为关键业务业务创建跨度
-   **鼻涕虫**: 建立具有亲子关系的复杂跟踪等级
-   **扩展属性**: 为丰富上下文添加自定义元数据
-   **Span 活动**:在跨度内增加加时标的检查站

### 🔍 **法罗一体化**

-   **用户动作关联**: Spans 与 Faro 用户动作相关
-   **日志关联**: 使用跟踪/扩展标识连接记录
-   **错误关联**: 错误自动链接到活动跨度
-   **计量关联**: 与痕迹挂钩的业绩计量

### 🛡️ **无限循环预防**

追踪仪器的精心设计是为了防止在追踪引起伐木时可能发生的无限回路,从而导致更多的追踪:

-   **自动 URL 过滤**: 收集器 URL 自动排除在追踪之外
-   **拖网斜线处理**: 处理 URL 变体( 有/ 没有跟踪斜线)
-   **内部日志**: 用途 `internalLogger` 改为 `console.log` 内部
-   **批处理**: 批次SpanProcessor 延迟跨出导出范围以避免阻塞
-   **导出时没有日志**: 微量导出时零控制台输出

## 配置选项

使用时 `enableTracing: true`,通过 `tracingOptions` 在你的法罗配置。 对于手动设置(例如自定义配置,不制作RNConfig),添加 `TracingInstrumentation` 改为 `instrumentations`数字 :

### 基本配置

```typescript
// Via flag (recommended):
initializeFaro({
  enableTracing: true,
  tracingOptions: {
    resourceAttributes: { 'deployment.environment': 'staging' },
    instrumentationOptions: {
      propagateTraceHeaderCorsUrls: [/https:\/\/api\.example\.com/],
    },
  },
});

// Or manually:
new TracingInstrumentation({
  // Optional: Add custom resource attributes
  resourceAttributes: {
    'service.namespace': 'mobile-apps',
    'deployment.environment': 'staging',
    'custom.attribute': 'value',
  },

  // Optional: Configure trace header propagation
  instrumentationOptions: {
    // URLs that should receive trace context headers
    propagateTraceHeaderCorsUrls: [/https:\/\/api\.example\.com/, 'https://other-api.com'],

    // Optional: enable XHR tracing for apps that use axios or XHR directly.
    // Disabled by default because React Native's current fetch implementation is backed by XHR.
    enableXhrInstrumentation: false,

    // Optional: Customize fetch instrumentation
    fetchInstrumentationOptions: {
      // Ignore network performance events (default: true)
      ignoreNetworkEvents: true,

      // Optional: Add custom attributes to spans
      applyCustomAttributesOnSpan: (span, request, response) => {
        span.setAttribute('http.custom', 'value');
        span.setAttribute('http.request_id', request.headers['x-request-id']);
      },
    },
  },
});
```

### 高级配置

```typescript
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { FaroTraceExporter, FaroMetaAttributesSpanProcessor } from '@grafana/faro-react-native-tracing';

new TracingInstrumentation({
  // Optional: Custom span processor (advanced)
  spanProcessor: new FaroMetaAttributesSpanProcessor(
    new BatchSpanProcessor(new FaroTraceExporter({ api: faro.api }), {
      scheduledDelayMillis: 1000,
      maxExportBatchSize: 30,
      maxQueueSize: 100,
    }),
    faro.metas
  ),

  // Optional: Custom OTEL instrumentations (advanced)
  instrumentations: [
    // Your custom OpenTelemetry instrumentations
  ],
});
```

当法罗移除并随后再添加追查仪器时,自定义跨度处理器仍然可以再用. 删除 冲出处理器而不关闭它。 通话 `TracingInstrumentation.shutdown()` 关闭它,并且是 该处理器的终端;在重新初始化仪器之前使用新的处理器.

## 用法实例

### 自动 HTTP 跟踪

`fetch()` 请求会被自动跟踪, 没有代码更改 :

```typescript
// This fetch call is automatically traced by default.
const response = await fetch('https://api.example.com/users');
const data = await response.json();

// The span includes:
// - HTTP method, URL, status code
// - Request/response headers (if configured)
// - Duration
// - Session ID, user info
// - Device metadata
```

### 轴心和直接XHR追踪

轴和直线 `XMLHttpRequest` 电话需要XHR仪器:

```typescript
initializeFaro({
  enableTracing: true,
  tracingOptions: {
    instrumentationOptions: {
      enableXhrInstrumentation: true,
    },
  },
});
```

如果同一应用程序也使用 `fetch()` 对于相同的后端 URL, 添加 `ignoreUrls` 以获取或XHR仪器来避免重复.

**追踪包括:**

-   `http.method`数字 : `GET`
-   `http.url`数字 : `https://api.example.com/users`
-   `http.status_code`数字 : `200`
-   `session.id`数字 : `abc123`
-   `device.model`数字 : `iPhone 15 Pro`
-   `device.platform`数字 : `iOS`
-   加上所有 Faro metas( 用户、 设备、 会话等)

### 手动扩展创建

为业务运行创建自定义跨度 :

```typescript
import { faro } from '@grafana/faro-react-native';

async function processOrder(orderId: string) {
  // Access OpenTelemetry API via faro.otel
  const { trace } = faro.otel;
  const tracer = trace.getTracer('my-app');

  // Create a span
  const span = tracer.startSpan('process-order', {
    attributes: {
      'order.id': orderId,
      'operation.type': 'payment',
    },
  });

  try {
    // Your business logic here
    const payment = await processPayment(orderId);

    // Add attributes as you go
    span.setAttribute('payment.amount', payment.amount);
    span.setAttribute('payment.currency', payment.currency);

    // Add an event (checkpoint)
    span.addEvent('payment_validated', {
      'validator.id': payment.validatorId,
    });

    // Mark span as successful
    span.setStatus({ code: SpanStatusCode.OK });
  } catch (error) {
    // Mark span as error
    span.setStatus({
      code: SpanStatusCode.ERROR,
      message: error.message,
    });
    span.recordException(error);
    throw error;
  } finally {
    // Always end the span
    span.end();
  }
}
```

### 亲子关系

建立复杂的跟踪等级:

```typescript
import { faro } from '@grafana/faro-react-native';
import { SpanStatusCode } from '@opentelemetry/api';

async function checkoutFlow(cartId: string) {
  const { trace, context } = faro.otel;
  const tracer = trace.getTracer('my-app');

  // Create parent span
  const parentSpan = tracer.startSpan('checkout-flow', {
    attributes: { 'cart.id': cartId },
  });

  try {
    // Use context.with() to make this span the active parent
    await context.with(trace.setSpan(context.active(), parentSpan), async () => {
      // Child span 1: Validate cart
      const validateSpan = tracer.startSpan('validate-cart');
      await validateCart(cartId);
      validateSpan.setStatus({ code: SpanStatusCode.OK });
      validateSpan.end();

      // Child span 2: Process payment
      const paymentSpan = tracer.startSpan('process-payment');
      await processPayment(cartId);
      paymentSpan.setStatus({ code: SpanStatusCode.OK });
      paymentSpan.end();

      // Child span 3: Send confirmation
      const confirmSpan = tracer.startSpan('send-confirmation');
      await sendConfirmation(cartId);
      confirmSpan.setStatus({ code: SpanStatusCode.OK });
      confirmSpan.end();
    });

    parentSpan.setStatus({ code: SpanStatusCode.OK });
  } catch (error) {
    parentSpan.setStatus({
      code: SpanStatusCode.ERROR,
      message: error.message,
    });
    parentSpan.recordException(error);
  } finally {
    parentSpan.end();
  }
}
```

### 与 Faro 用户动作的关联

Spans 自动与用户动作相关 :

```typescript
import { faro } from '@grafana/faro-react-native';
import { withFaroUserAction } from '@grafana/faro-react-native';
import { TouchableOpacity } from 'react-native';

// Create a tracked button
const TrackedButton = withFaroUserAction(TouchableOpacity, 'load-data');

function DataLoader() {
  const handleLoad = async () => {
    // This fetch will be traced AND correlated with the user action
    // The span will include: faro.action.user.name = "load-data"
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
  };

  return (
    <TrackedButton onPress={handleLoad}>
      <Text>Load Data</Text>
    </TrackedButton>
  );
}
```

### 与 Faro 日志关联

用日志连接可完全可观察的痕迹 :

```typescript
import { faro } from '@grafana/faro-react-native';
import { SpanStatusCode } from '@opentelemetry/api';

function performOperation() {
  const { trace, context } = faro.otel;
  const tracer = trace.getTracer('my-app');
  const span = tracer.startSpan('important-operation');

  // Run operation within span context
  context.with(trace.setSpan(context.active(), span), () => {
    // This log will be correlated with the span
    // via trace_id and span_id in the log meta
    faro.api.pushLog(['Operation started'], {
      context: 'operations',
      level: 'info',
    });

    // Do work...

    faro.api.pushLog(['Operation completed successfully'], {
      context: 'operations',
      level: 'info',
    });

    span.setStatus({ code: SpanStatusCode.OK });
    span.end();
  });
}
```

## 如何运作

### 建筑

```
┌─────────────────────────────────────────────────────────────┐
│                    Your React Native App                     │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       │ fetch() / XHR calls
                       ↓
┌─────────────────────────────────────────────────────────────┐
│       FetchInstrumentation, optionally XMLHttpRequest        │
│  • Intercepts fetch() by default                            │
│  • Creates spans automatically                               │
│  • Propagates W3C Trace Context headers                      │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       │ Spans
                       ↓
┌─────────────────────────────────────────────────────────────┐
│     HttpRequestMonitorSpanProcessor (user action correlation) │
│  • Notifies httpRequestMonitor for user action halt logic    │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       │ Spans
                       ↓
┌─────────────────────────────────────────────────────────────┐
│           FaroMetaAttributesSpanProcessor                    │
│  • Adds Faro metas (session, user) to spans                  │
│  • Device/service from resource                              │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       │ Enriched spans
                       ↓
┌─────────────────────────────────────────────────────────────┐
│              BatchSpanProcessor (OTEL)                       │
│  • Batches spans (max 30, delay 1000ms)                     │
│  • Reduces network requests                                  │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       │ Span batches
                       ↓
┌─────────────────────────────────────────────────────────────┐
│                 FaroTraceExporter                            │
│  • Converts spans to OTLP format                             │
│  • Sends to Faro collector via pushTraces()                  │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       │ OTLP/HTTP
                       ↓
┌─────────────────────────────────────────────────────────────┐
│              Grafana Cloud / Faro Collector                  │
│  • Receives traces                                           │
│  • Stores in Tempo                                           │
│  • Links traces ↔ logs ↔ metrics                             │
└─────────────────────────────────────────────────────────────┘
```

### Span 寿命周期

1.  **扩展创建**: Fellow 仪器在取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取 如果 URL 匹配, 请求中会添加 W3C 追踪上下文头 `propagateTraceHeaderCorsUrls`。 。 。 .
2.  **浓缩**: Http RequestMonitorSpanProcessor 通知用户动作关联性; FaroMetaPizesSpanProcessor 添加会话和用户间距(device/service来自资源)
3.  **击打**: 批量斯潘处理器收集跨度(最大为30个跨度或1000ms延迟)
4.  **导出**:FaroTraceExporter将跨度转换为OTLP格式;也发送Faro事件(例如. `faro.tracing.fetch`CLIENT 跨度
5.  **传送**: Spans通过 `faro.api.pushTraces()`当SDK的核心 `batching` 选项,在发送前,导出的时间段会与其他信号一起排队.

### 扩展属性

每个跨度包括这些属性:

**标准 OTEL 属性 :**

-   `http.method` - HTTP方法(GET、POST等)
-   `http.url` - 完整 URL 语句
-   `http.status_code` - HTTP状态代码
-   `http.target` - URL路径

**法罗会话属性 :**

-   `session.id` - 法罗会话编号

**用户属性( 如果设置 ) :**

-   `user.id` - 用户代号
-   `user.name` - 用户名
-   `user.email` - 电子邮件

**设备属性( 来自资源) :**

-   `device.model` - 设备模型(例如"iPhone 15 Pro")
-   `device.brand` - 设备制造商(例如: "Apple")
-   `device.platform` - OS名称(例如"iOS")
-   `device.os.version` -OS版本(如"17.0")
-   `device.locale` - 设备本地化(例如“在美国”)

**应用程序属性( 来自资源) :**

-   `service.name` - 来自配置的应用名称
-   `service.version` - App 版本
-   `service.namespace` - App 命名空间( 如果设置)
-   `deployment.environment.name` - 环境(生产、装配等)

**用户动作属性( 如果活动) :**

-   `faro.action.user.name` - 用户动作名称
-   `faro.action.user.parentId` - 父母行动ID

## 分布式追踪

### 连接前端到后端

要启用完整的分布式跟踪, 请配置您的后端以接受 W3C Trace 背景头 :

```typescript
// Frontend (React Native)
new TracingInstrumentation({
  instrumentationOptions: {
    // Propagate headers to your API
    propagateTraceHeaderCorsUrls: [/https:\/\/api\.example\.com/],
  },
});

// Backend (Node.js + Express + OpenTelemetry)
const { W3CTraceContextPropagator } = require('@opentelemetry/core');
const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');

const provider = new NodeTracerProvider();
provider.register({
  propagator: new W3CTraceContextPropagator(),
});
```

正确配置时 :

1.  前端为 HTTP 请求创建跨度
2.  前端添加 `traceparent` 财务报告和审定财务报表 `tracestate` 请求头
3.  后端提取信头的微量上下文
4.  后端创建与前端跟踪链接的子间隔
5.  前端和后端的跨度都出现在格拉法纳的相同痕跡中

### 分发的线索示例

```
Trace: abc123-def456-ghi789

├─ [Frontend] fetch POST /api/orders (250ms)
│  ├─ [Backend] POST /api/orders (200ms)
│  │  ├─ [Backend] validate-order (10ms)
│  │  ├─ [Backend] query-database (150ms)
│  │  └─ [Backend] send-email (40ms)
│  └─ [Frontend] parse-response (5ms)
```

## 解决问题

### 格拉法纳云里没有痕迹

**检查会话采样 :**

```typescript
const session = faro.api.getSession();
console.log('Session:', session);
console.log('Is sampled:', session?.attributes?.isSampled);
```

若为 `isSampled` 是虚假的,不会收集痕迹。 在 SDK 配置中调整会话采样( 缩写) `sampling` 100%):

```typescript
import { initializeFaro, SamplingRate } from '@grafana/faro-react-native';

initializeFaro({
  // ...
  sessionTracking: {
    sampling: new SamplingRate(1), // 100% of sessions
  },
});
```

**校验收藏器 URL :**

```typescript
// Check that URL is correctly formatted
console.log('Collector URL:', faro.config.url);
```

**检查网络请求 :** 打开回放本地调试器 ~ 网络标签 ~ 查找 POST 请求到 `/collect/`

### 无限循环/ 指数请求

**症状:**

-   App发送指数增长的请求
-   App变得没有反应
-   Dev 工具崩溃

**原因 :** 追踪出口请求正在被追踪,从而形成无限循环.

**解决方案 :** 应自动防止这种情况。 如果你经历这个问题:

1.  **更新到最新版本** - 在最近的版本中确定了无限循环预防
2.  **检查自定义跨度处理器** - 别用 `console.log` 在自定义处理器中
3.  **校验 URL 过滤** - 收集器URL应自动排除

```typescript
// Debug: Check which URLs are being ignored
const ignoredUrls = transport.getIgnoreUrls();
console.log('Ignored URLs:', ignoredUrls);
```

### OTEL 不可用错误

**错误 :**

```
OTEL is not available. Make sure tracing is initialised
```

**原因 :** 尝试使用 `faro.otel` 在追踪工具初始化之前.

**解决方案 :**

```typescript
// ✅ Correct: Initialize tracing first
const faro = initializeFaro({
  instrumentations: [new TracingInstrumentation()],
});

// Then use faro.otel
const { trace } = faro.otel;

// ❌ Wrong: Using faro.otel without tracing instrumentation
const faro = initializeFaro({
  instrumentations: [], // No tracing!
});
const { trace } = faro.otel; // Error!
```

### 追踪ID是零码(00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

**原因 :** Tracer Provider不注册为全球供应商.

**解决方案 :** 这应该是自动的。 如果你使用自定义跨度处理器或自定义仪器,确保你不会凌驾于追踪器提供者注册之上.

如果另一个全球的 OpenTeleometry 追踪器提供者已经注册, 追踪初始化失败, 并明确 错误而不是安装无法通过法罗导出的请求仪器 。 删除重复的提供者 初始化前的登记 `TracingInstrumentation`。 。 。 .

### 缺少用户/会议/设备的背景

**原因 :** FaroMeta 属性SpanProcessor 没有包入您的跨度处理器 .

**解决方案 :** 使用默认的跨度处理器或确保您包装您的自定义处理器:

```typescript
import { FaroMetaAttributesSpanProcessor } from '@grafana/faro-react-native-tracing';

new TracingInstrumentation({
  spanProcessor: new FaroMetaAttributesSpanProcessor(yourCustomSpanProcessor, faro.metas),
});
```

### 后端跨度未出现在前端跟踪

**原因 :** 后端没有配置以接受W3C Trace上下文头,或者CORS正在屏蔽头.

**解决方案 :**

1.  **在后端启用 W3C 显示器 :**

```javascript
// Node.js + OpenTelemetry
const { W3CTraceContextPropagator } = require('@opentelemetry/core');
provider.register({
  propagator: new W3CTraceContextPropagator(),
});
```

2.  **配置允许跟踪头的 CORS :**

```javascript
// Express
app.use(
  cors({
    allowedHeaders: ['traceparent', 'tracestate'],
  })
);
```

3.  **在传播列表中添加后端 URL :**

```typescript
new TracingInstrumentation({
  instrumentationOptions: {
    propagateTraceHeaderCorsUrls: [/https:\/\/your-backend\.com/],
  },
});
```

## API 参考

### 追查文书

分布式追踪的主要仪器类.

```typescript
class TracingInstrumentation extends BaseInstrumentation {
  constructor(options?: TracingInstrumentationOptions);
  initialize(): void;
  shutdown(): Promise<void>;
  destroy(): void;
}
```

`shutdown()` 在等待追踪器提供者冲出前解析出 HTTP 仪表 。 法罗打电话 `destroy()` 当仪器被移除时;它立即解析,并在背景中完成提供者的关闭. 这两种方法都能够安全地多次拨打.

当追踪被移除并随后再添加时,再利用同样内容 `TracingInstrumentation` 实例,所以默认获取 和XHR补丁也被再用.

**选项 :**

```typescript
interface TracingInstrumentationOptions {
  // Custom OTEL resource attributes
  resourceAttributes?: Attributes;

  // Custom OTEL propagator (default: W3CTraceContextPropagator)
  propagator?: TextMapPropagator;

  // Custom OTEL context manager (default: StackContextManager)
  contextManager?: ContextManager;

  // Custom OTEL instrumentations (replaces default fetch/XHR instrumentations)
  instrumentations?: Instrumentation[];

  // Custom span processor (replaces default BatchSpanProcessor)
  spanProcessor?: SpanProcessor;

  // Instrumentation options
  instrumentationOptions?: {
    // URLs to propagate trace headers to
    propagateTraceHeaderCorsUrls?: Array<string | RegExp>;

    // Enable fetch instrumentation (default: true)
    enableFetchInstrumentation?: boolean;

    // Enable XHR instrumentation (default: false)
    enableXhrInstrumentation?: boolean;

    // Fetch instrumentation options
    fetchInstrumentationOptions?: {
      // Custom attributes function
      applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;

      // Ignore network events (default: true)
      ignoreNetworkEvents?: boolean;
    };
  };
}
```

### 法罗追踪输出器

向法罗收藏家输出 OpenTeleometry 跨度 .

```typescript
class FaroTraceExporter implements SpanExporter {
  constructor(config: FaroTraceExporterConfig);
  export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
  shutdown(): Promise<void>;
}
```

### (a) 电信设备

返回默认的本地反应的 OpenTelemeth 仪器 .

```typescript
function getDefaultOTELInstrumentations(options?: DefaultInstrumentationsOptions): Instrumentation[];
```

当前返回 :

-   `FetchInstrumentation` - 自动跟踪HTTP
-   `XMLHttpRequestInstrumentation` - 可选;启用方式 `enableXhrInstrumentation: true`

### faro.otel (法语)

访问 OpenTeleometry API 用于手动跟踪.

```typescript
interface FaroOTEL {
  trace: TraceAPI; // OpenTelemetry trace API
  context: ContextAPI; // OpenTelemetry context API
}

// Usage
const { trace, context } = faro.otel;
const tracer = trace.getTracer('my-app');
const span = tracer.startSpan('operation');
```

## 最佳做法

### {\\FN黑体\\FS22\\BORD1\\SHAD0\\3AHBE\\4AH00\\FSCX67\\FSCY66\\2CHFFFFFF\\3CH808080}请说

-   **使用自动跟踪** - 让获取仪器处理 HTTP 请求
-   **添加有意义的属性** - 将业务背景纳入跨度范围
-   **使用跨度事件** - 为重要行动增设检查站
-   **设定跨度状态** - 标记跨度为确定或错误
-   **结束间距** - 总是打电话 `span.end()` 终于来了
-   **使用上下文. with( )** - 对于被窝住的地段
-   **与用户动作关联** - 使用( I) `withFaroUserAction` 韩克
-   **配置传播** - 将您的 API 添加到 `propagateTraceHeaderCorsUrls`
-   **抽样会议** - 高流量应用软件的取样

### 别

-   **在跨度处理器中不要使用控制台.log** - 造成无限循环
-   **不要忘记结束的跨度** - 造成内存泄漏
-   **不要为小动作创造跨度** - 追踪量合理
-   **跨度属性中不要包含 PII** - 尊重用户隐私
-   **不要追踪内部URL** - 收集器 URL 自动排除
-   **不要创造出深厚的花圈** - 保持分级( < 10级)

## 实例

完整的示例请参见演示应用程序 :

-   [追踪DemoScreen.tsx](https://npmcn.com/package/demo/src/screens/TracingDemoScreen.tsx) - 10个全面追踪情况
-   [初始化.ts](https://npmcn.com/package/demo/src/faro/initialize.ts) - 法罗初始化并追踪

## 业绩考量

### 间接费用

-   **自动跟踪**: ~ 5- 10 ms / HTTP 请求
-   **手动跨度**: ~0.5-1米(每平方厘米)
-   **批处理**: 最小撞击(1 000ms延迟)

### 优化提示

1.  **抽样会议** - 不要跟踪每场会议:

```typescript
import { SamplingRate } from '@grafana/faro-react-native';

// ...
sessionTracking: {
  sampling: new SamplingRate(0.1), // 10% of sessions
}
```

2.  **增加批量大小** - 减少网络请求:

```typescript
new BatchSpanProcessor(exporter, {
  maxExportBatchSize: 50, // Default: 30
  scheduledDelayMillis: 2000, // Default: 1000
});
```

3.  **过滤跨度** - 不要追踪一切:

```typescript
fetchInstrumentationOptions: {
  applyCustomAttributesOnSpan: (span, request) => {
    // Skip internal requests
    if (request.url.includes('/health')) {
      span.setAttribute('skip', true);
    }
  },
}
```

## 类型脚本

软件包用TypeScript来写,包括类型定义.

```typescript
import type {
  TracingInstrumentationOptions,
  FaroTraceExporterConfig,
  DefaultInstrumentationsOptions,
} from '@grafana/faro-react-native-tracing';
```

## 许可证

阿帕奇 - 2.0

## 捐款

见主仓库 [捐款额](https://npmcn.com/package/CONTRIBUTING.md) 捐款准则.

## 支助

-   📖 [文档](https://grafana.com/docs/grafana-cloud/monitor-applications/frontend-observability/)
-   💬 [GitHub 讨论](https://github.com/grafana/faro-react-native-sdk/discussions)
-   🐛 [问题跟踪器](https://github.com/grafana/faro-react-native-sdk/issues)

## 常见问题

### @grafana/faro-react-native-tracing 是什么？

Faro React Industrial tracking explocation with OpenTeleometry\. 法罗反应原生追踪与OpenTeleometry的实现\.

### 如何安装 @grafana/faro-react-native-tracing？

在项目目录运行 npm install @grafana/faro-react-native-tracing，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react-native（\>=0\.70\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @grafana/faro-react-native-tracing 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @grafana/faro-react-native-tracing 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @grafana/faro-react-native-tracing 可以商用吗？

@grafana/faro-react-native-tracing 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @grafana/faro-react-native-tracing 的下载量有多少？

根据 npm 官方下载统计，@grafana/faro-react-native-tracing 在 2026/10/17 – 2026/11/15 这 30 天内被下载 15,676 次，日均约 523 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @grafana/faro-react-native-tracing 还在维护吗？

最新版本 2\.0\.4 发布于 2026/10/28（19 天前）；至今共发布 12 个版本，其中过去 12 个月发布了 12 个；首次发布于 2026/03/31。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

