@grafana/faro-resact-native-tracting (英语)
OpenTeleometry分布式跟踪集成法罗反应原生SDK.
安装
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数字 :
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公约, (中文(简体) ),
带有诸如 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能够明确追踪:
initializeFaro({
enableTracing: true,
tracingOptions: {
instrumentationOptions: {
enableXhrInstrumentation: true,
},
},
});
如果你的应用程序同时使用 fetch() 并避免两次追查同一请求。 或只追踪一个 API 表面:
initializeFaro({
enableTracing: true,
tracingOptions: {
instrumentationOptions: {
// Useful for axios/direct XHR apps.
enableFetchInstrumentation: false,
enableXhrInstrumentation: true,
},
},
});
或既允许又允许使用 ignoreUrls 在一个仪器上,所以 URL 模式不会重叠 :
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数字 :
基本配置
// 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']);
},
},
},
});
高级配置
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() 请求会被自动跟踪, 没有代码更改 :
// 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仪器:
initializeFaro({
enableTracing: true,
tracingOptions: {
instrumentationOptions: {
enableXhrInstrumentation: true,
},
},
});
如果同一应用程序也使用 fetch() 对于相同的后端 URL, 添加 ignoreUrls 以获取或XHR仪器来避免重复.
追踪包括:
http.method数字 :GEThttp.url数字 :https://api.example.com/usershttp.status_code数字 :200session.id数字 :abc123device.model数字 :iPhone 15 Prodevice.platform数字 :iOS- 加上所有 Faro metas( 用户、 设备、 会话等)
手动扩展创建
为业务运行创建自定义跨度 :
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();
}
}
亲子关系
建立复杂的跟踪等级:
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 自动与用户动作相关 :
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 日志关联
用日志连接可完全可观察的痕迹 :
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 寿命周期
- 扩展创建: Fellow 仪器在取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取 如果 URL 匹配, 请求中会添加 W3C 追踪上下文头
propagateTraceHeaderCorsUrls。 。 。 . - 浓缩: Http RequestMonitorSpanProcessor 通知用户动作关联性; FaroMetaPizesSpanProcessor 添加会话和用户间距(device/service来自资源)
- 击打: 批量斯潘处理器收集跨度(最大为30个跨度或1000ms延迟)
- 导出:FaroTraceExporter将跨度转换为OTLP格式;也发送Faro事件(例如.
faro.tracing.fetchCLIENT 跨度 - 传送: 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 背景头 :
// 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(),
});
正确配置时 :
- 前端为 HTTP 请求创建跨度
- 前端添加
traceparent财务报告和审定财务报表tracestate请求头 - 后端提取信头的微量上下文
- 后端创建与前端跟踪链接的子间隔
- 前端和后端的跨度都出现在格拉法纳的相同痕跡中
分发的线索示例
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)
解决问题
格拉法纳云里没有痕迹
检查会话采样 :
const session = faro.api.getSession();
console.log('Session:', session);
console.log('Is sampled:', session?.attributes?.isSampled);
若为 isSampled 是虚假的,不会收集痕迹。 在 SDK 配置中调整会话采样( 缩写) sampling 100%):
import { initializeFaro, SamplingRate } from '@grafana/faro-react-native';
initializeFaro({
// ...
sessionTracking: {
sampling: new SamplingRate(1), // 100% of sessions
},
});
校验收藏器 URL :
// Check that URL is correctly formatted
console.log('Collector URL:', faro.config.url);
检查网络请求 :
打开回放本地调试器 ~ 网络标签 ~ 查找 POST 请求到 /collect/
无限循环/ 指数请求
症状:
- App发送指数增长的请求
- App变得没有反应
- Dev 工具崩溃
原因 : 追踪出口请求正在被追踪,从而形成无限循环.
解决方案 : 应自动防止这种情况。 如果你经历这个问题:
- 更新到最新版本 - 在最近的版本中确定了无限循环预防
- 检查自定义跨度处理器 - 别用
console.log在自定义处理器中 - 校验 URL 过滤 - 收集器URL应自动排除
// 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 在追踪工具初始化之前.
解决方案 :
// ✅ 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 没有包入您的跨度处理器 .
解决方案 : 使用默认的跨度处理器或确保您包装您的自定义处理器:
import { FaroMetaAttributesSpanProcessor } from '@grafana/faro-react-native-tracing';
new TracingInstrumentation({
spanProcessor: new FaroMetaAttributesSpanProcessor(yourCustomSpanProcessor, faro.metas),
});
后端跨度未出现在前端跟踪
原因 : 后端没有配置以接受W3C Trace上下文头,或者CORS正在屏蔽头.
解决方案 :
- 在后端启用 W3C 显示器 :
// Node.js + OpenTelemetry
const { W3CTraceContextPropagator } = require('@opentelemetry/core');
provider.register({
propagator: new W3CTraceContextPropagator(),
});
- 配置允许跟踪头的 CORS :
// Express
app.use(
cors({
allowedHeaders: ['traceparent', 'tracestate'],
})
);
- 在传播列表中添加后端 URL :
new TracingInstrumentation({
instrumentationOptions: {
propagateTraceHeaderCorsUrls: [/https:\/\/your-backend\.com/],
},
});
API 参考
追查文书
分布式追踪的主要仪器类.
class TracingInstrumentation extends BaseInstrumentation {
constructor(options?: TracingInstrumentationOptions);
initialize(): void;
shutdown(): Promise<void>;
destroy(): void;
}
shutdown() 在等待追踪器提供者冲出前解析出 HTTP 仪表 。 法罗打电话 destroy()
当仪器被移除时;它立即解析,并在背景中完成提供者的关闭.
这两种方法都能够安全地多次拨打.
当追踪被移除并随后再添加时,再利用同样内容 TracingInstrumentation 实例,所以默认获取
和XHR补丁也被再用.
选项 :
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 跨度 .
class FaroTraceExporter implements SpanExporter {
constructor(config: FaroTraceExporterConfig);
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void;
shutdown(): Promise<void>;
}
(a) 电信设备
返回默认的本地反应的 OpenTelemeth 仪器 .
function getDefaultOTELInstrumentations(options?: DefaultInstrumentationsOptions): Instrumentation[];
当前返回 :
FetchInstrumentation- 自动跟踪HTTPXMLHttpRequestInstrumentation- 可选;启用方式enableXhrInstrumentation: true
faro.otel (法语)
访问 OpenTeleometry API 用于手动跟踪.
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 - 10个全面追踪情况
- 初始化.ts - 法罗初始化并追踪
业绩考量
间接费用
- 自动跟踪: ~ 5- 10 ms / HTTP 请求
- 手动跨度: ~0.5-1米(每平方厘米)
- 批处理: 最小撞击(1 000ms延迟)
优化提示
- 抽样会议 - 不要跟踪每场会议:
import { SamplingRate } from '@grafana/faro-react-native';
// ...
sessionTracking: {
sampling: new SamplingRate(0.1), // 10% of sessions
}
- 增加批量大小 - 减少网络请求:
new BatchSpanProcessor(exporter, {
maxExportBatchSize: 50, // Default: 30
scheduledDelayMillis: 2000, // Default: 1000
});
- 过滤跨度 - 不要追踪一切:
fetchInstrumentationOptions: {
applyCustomAttributesOnSpan: (span, request) => {
// Skip internal requests
if (request.url.includes('/health')) {
span.setAttribute('skip', true);
}
},
}
类型脚本
软件包用TypeScript来写,包括类型定义.
import type {
TracingInstrumentationOptions,
FaroTraceExporterConfig,
DefaultInstrumentationsOptions,
} from '@grafana/faro-react-native-tracing';
许可证
阿帕奇 - 2.0
捐款
见主仓库 捐款额 捐款准则.