This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo 观察
一个收集应用性能指标和用户自定义事件并将它们发送到 EAS Observe 的库。
信息 EAS Observe 在免费计划中每月包含 100,000 个事件,在付费计划中包含 500,000 个事件,大约对应每月 10,000 和 50,000 的活跃用户。超出部分则按使用量计费。详情请参见 定价。
expo-observe 是一个库,它可以收集你应用的性能指标和用户自定义事件,并将它们发送到 EAS Observe —— Expo 的性能监控服务,或者你喜欢的任何符合 OpenTelemetry (OTEL) 标准的后台。它可以测量真实环境下的启动性能,比如 首屏渲染时间 (TTR) 和 可交互时间 (TTI),针对在生产环境运行的应用。
除了应用启动指标,这个库还可以:
🌐 Beyond app startup metrics, the library can also:
- 使用 Expo Router 或 React Navigation 集成收集每条路由的导航指标。
- 使用
Observe.logEvent记录 用户自定义事件。 - 自动跟踪 EAS 更新下载时间。
- 使用
ObserveErrorBoundary和Observe.reportError记录 JavaScript 错误,并在 EAS Observe 仪表板(预览)中通过符号化堆栈跟踪查看它们。 - 让第三方包可以用
Observe.registerIntegration注册它们自己的集成。
警告
expo-observe在 Expo Go 中不可用。要使用它,请创建一个 开发构建。
安装
🌐 Installation
If you are installing this in an existing React Native app, make sure to install expo in your project.
配置
🌐 Configuration
在发布版本中,安装“expo-observe”库即可配置库开始发送启动指标(不过你需要按照以下使用说明调用“markInteractive”来跟踪TTI)。该库不会在调试构建中发送事件,但你可以更改此及其他配置选项,如采样率、环境名称以及启用与“Observe.configure()”调用的集成。所有可用选项请参见[EAS Observe 配置指南](/eas/observe/configuration/)。
🌐 In release builds, installing the expo-observe library is all that is needed to configure the library to start sending startup metrics (though you will need to follow the usage instructions below to call markInteractive to track TTI). The library will not dispatch events in debug builds, but you can change this and other config options such as sample rate, environment name and enabling integrations with the Observe.configure({}) call. For all available options, see the EAS Observe configuration guide.
用法
🌐 Usage
将你的根布局用 ObserveRoot 封装,以自动测量首次渲染时间。然后,当你的应用准备好供用户交互时,调用 markInteractive 来记录可交互时间:
🌐 Wrap your root layout with ObserveRoot to measure Time to First Render automatically. Then, call markInteractive when your app is ready for user interaction to record Time to Interactive:
有关逐步说明,包括完整的启动屏示例以及如何处理具有多个入口屏的应用,请参阅 EAS Observe 入门指南。要从你的应用发送自定义事件,请参阅 用户自定义事件。
🌐 For step-by-step instructions, including a complete splash screen example and how to handle apps with multiple entry screens, see the EAS Observe Get started guide. To send custom events from your app, see User-defined events.
应用接口
🌐 API
import { Observe, ObserveRoot, useObserve } from 'expo-observe';
Components
Type: React.Component<AppMetricsErrorBoundaryProps, State>
A React error boundary that records render-phase errors as non-fatal exception log events (with
the React component stack) and renders a fallback in place of the subtree that threw.
Render-phase errors don't reach global.ErrorUtils, so a boundary is the only way to capture them
with the component stack. Place one around any subtree, or let AppMetricsRoot mount one via its
errorBoundaryFallback prop.
Type: React.Element<ObserveInteractiveMarkerProps>
Declarative wrapper around useObserve().markInteractive(...). Renders nothing
and calls markInteractive once when it first mounts, marking the moment the
screen becomes interactive (used to compute the tti metric). Render it once
the screen is ready for user interaction — for example, after its initial data
has loaded.
Because markInteractive is only sent on mount, the marker is fire-once: changing
params after the first render has no effect and warns in development. If you need
to attach attributes that are only known later, call useObserve().markInteractive(...)
imperatively instead.
Example
import { ObserveInteractiveMarker } from 'expo-observe'; function Feed({ items }) { if (!items) return <Spinner />; return ( <> <FeedList items={items} /> <ObserveInteractiveMarker params={{ cacheHit: true }} /> </> ); }
Type: React.Element<AppMetricsRootProps & {
children: ReactNode
}>
Static methods
Component methods
Hooks
{
markInteractive: (attributes: MetricAttributes) => void
}Interfaces
ExpoAppMetricsModuleType Methods
Promise<void>Records a log event against the current main session. The event is
persisted locally and dispatched on the next dispatchEvents() flush as an
OpenTelemetry log record sent to the /v1/logs endpoint.
Severity defaults to "info" when not provided.
voidSets attributes merged into every subsequent metric and log event.
Per-record keys win on collision. Pass null, undefined, or an empty
object to clear.
voidExample
AppMetrics.setGlobalAttributes({ subscription_tier: 'pro', experiment_variant: 'B', });
Extends: NativeModule<ObserveModuleEvents>
Configures how observability events are collected and dispatched at runtime, such as the environment label, dispatching behavior, sampling, and integrations.
voidExample
import { Observe } from 'expo-observe'; Observe.configure({ environment: 'production', dispatchingEnabled: true, });
Dispatches pending events to the server immediately.
Events are dispatched automatically when the app moves to the background. On Android, a background worker dispatches events once network connectivity is available. On iOS, dispatching happens when the app resigns active state or is about to terminate. Call this method to flush events manually, for example, during testing or to ensure events are sent before a specific point.
Promise<void>A promise that resolves when the pending events have been dispatched.
Example
import { Observe } from 'expo-observe'; await Observe.dispatchEvents();
Returns the integrations config from the most recent configure(...)
call, or an empty object if configure has not run yet.
ObserveIntegrationsConfigRecords a log event against the current main session. The event is
persisted locally and dispatched on the next dispatchEvents() flush.
Severity defaults to "info" when not provided.
voidMarks the first render of the app. Used to compute the cold_ttr and
warm_ttr metrics.
voidMarks the moment the app becomes interactive. Used to compute the tti
metric. Custom routeName and params can be attached via attributes.
Note: When the
expo-routeror@react-navigation/nativeintegration is active, preferuseObserve().markInteractive(...)— the hook fills inrouteNamefrom the current route, while this raw call does not.
voidInvokes a callback once when the named integration configuration becomes available.
voidExample
Observe.registerIntegration('expo-router', config => { console.log(config); });
Reports an error your code caught and handled, recorded as a non-fatal exception event. Use it
to keep visibility into failures you recover from, which never reach the automatic global handler
or an error boundary.
The thrown value is normalized: an Error's name, message, and stack are captured; any
other value (a string, a plain object) is stringified as the message.
voidExample
try { await syncCart(); } catch (error) { Observe.reportError(error); }
Pushes JS-bundle-derived facts (process.env.NODE_ENV, __DEV__) into native
storage. Called automatically once when the package is first imported; should
not be called by host apps directly.
voidTypes
Value types accepted in a log event's attributes map. Strings, numbers,
and booleans are stored as typed primitives; arrays and nested maps preserve
their structure. Other JS values (functions, Date, undefined, etc.) are
not supported and may be dropped by downstream consumers.
Type: string or number or boolean or object shaped as below:
Optional configuration accepted by logEvent. The event name is passed as
the first positional argument since it's required and the only field most
callers set.
Literal type: string
Severity of a log event, ordered from least to most severe:
"trace"— Fine-grained tracing, typically only useful while reproducing a specific issue."debug"— Diagnostic detail useful during development; usually filtered out in production."info"— Routine, expected events that record normal app behavior."warn"— Unexpected but recoverable conditions worth investigating."error"— An operation failed; the app continues running but is in a degraded state."fatal"— A severe failure, often immediately followed by app termination.
Acceptable values are: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'
Type: LogAttributeValue
Value types accepted as attribute values in setGlobalAttributes and the
other Observe APIs. Strings, numbers, and booleans are stored as typed
primitives; arrays and nested maps preserve their structure.
Type: Record<string, ObserveAttribute>
A map of attribute key to value, as accepted by setGlobalAttributes and
other Observe APIs that take a free-form attributes payload.