Reference version

This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo Observe iconExpo Observe

一个用于收集应用性能指标和用户自定义事件,并将其发送到 EAS Observe 的库。

Android
iOS
tvOS
Recommended version:
~56.0.29

expo-observe 是一个库,可从你的应用中收集性能指标和用户自定义事件,并将它们发送到 EAS Observe(Expo 提供的性能监控服务),或发送到你首选的、符合 OpenTelemetry(OTEL)规范的后端。它会测量生产环境中运行的应用的真实启动性能,例如首次渲染时间(TTR)和可交互时间(TTI)。

除应用启动指标外,该库还可以:

安装

Terminal
- npx expo install expo-observe
- yarn expo install expo-observe
- pnpm expo install expo-observe
- bun expo install expo-observe

If you are installing this in an existing React Native app, make sure to install expo in your project.

配置

在发布构建中,安装 expo-observe 库即可配置该库并开始发送启动指标(不过,你需要按照下方的使用说明调用 markInteractive 来跟踪 TTI)。该库不会在调试构建中发送事件,但你可以通过调用 Observe.configure({}) 更改此行为以及其他配置选项,例如采样率、环境名称和启用集成。有关所有可用选项,请参阅 EAS Observe 配置指南。

使用方法

使用 ObserveRoot 包裹根布局,即可自动测量首次渲染时间。然后,在应用准备好供用户交互时调用 markInteractive,以记录可交互时间:

src/app/_layout.tsx
import { ObserveRoot, useObserve } from 'expo-observe'; import { Stack } from 'expo-router'; import { useEffect } from 'react'; function RootLayout() { const { markInteractive } = useObserve(); useEffect(() => { // Replace this effect with your own readiness signal: only call // markInteractive() after initialization work behind the splash screen // (such as loading initial data) completes. markInteractive(); }, [markInteractive]); return <Stack />; } export default ObserveRoot.wrap(RootLayout);

有关分步说明,包括完整的启动屏幕示例以及如何处理具有多个入口屏幕的应用,请参阅 EAS Observe 入门指南。要从应用发送自定义事件,请参阅用户自定义事件。

API

import { Observe, ObserveRoot, useObserve } from 'expo-observe';

Component

ObserveRoot

Android
iOS
tvOS

Type: React.Element<{ children: ReactNode } & { children: ReactNode }>

Component methods

wrap(Component)

Android
iOS
tvOS
ParameterType
ComponentComponentType<P>

Returns:
ComponentType<P>

Hooks

useObserve()

Android
iOS
tvOS
Returns:
{ markInteractive: (attributes: MetricAttributes) => void }

Interfaces

ExpoAppMetricsModuleType

Android
iOS
tvOS

ExpoAppMetricsModuleType Methods

clearStoredEntries()

Android
iOS
tvOS
Returns:
Promise<void>

logEvent(name, options)

Android
iOS
tvOS
ParameterTypeDescription
namestring

Event name. Maps to the OpenTelemetry event.name attribute.

options(optional)LogEventOptions

Optional body, attributes, and severity overrides.


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.

Returns:
void

markFirstRender()

Android
iOS
tvOS
Returns:
void

markInteractive(attributes)

Android
iOS
tvOS
ParameterType
attributes(optional)MetricAttributes

Returns:
void

setGlobalAttributes(attributes)

Android
iOS
tvOS
ParameterType
attributes(optional)Record<string, LogAttributeValue> | null

Sets attributes merged into every subsequent metric and log event. Per-record keys win on collision. Pass null, undefined, or an empty object to clear.

Returns:
void

Example

AppMetrics.setGlobalAttributes({ subscription_tier: 'pro', experiment_variant: 'B', });

ObserveModule

Android
iOS
tvOS

Extends: NativeModule

ObserveModule Methods

configure(config)

Android
iOS
tvOS
ParameterTypeDescription
configObserveConfig

Observability settings to apply.


Configures how observability events are collected and dispatched at runtime, such as the environment label, dispatching behavior, sampling, and integrations.

Returns:
void

Example

import { Observe } from 'expo-observe'; Observe.configure({ environment: 'production', dispatchingEnabled: true, });

dispatchEvents()

Android
iOS
tvOS

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.

Returns:
Promise<void>

A promise that resolves when the pending events have been dispatched.

Example

import { Observe } from 'expo-observe'; await Observe.dispatchEvents();

logEvent(name, options)

Android
iOS
tvOS
ParameterTypeDescription
namestring

Event name.

options(optional)LogEventOptions

Optional body, attributes, and severity overrides.


Records 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.

Returns:
void

markFirstRender()

Android
iOS
tvOS

Marks the first render of the app. Used to compute the cold_ttr and warm_ttr metrics.

Returns:
void

markInteractive(attributes)

Android
iOS
tvOS
ParameterType
attributes(optional)MetricAttributes

Marks the moment the app becomes interactive. Used to compute the tti metric. Custom routeName and params can be attached via attributes.

Returns:
void

setBundleDefaults(defaults)

Android
iOS
tvOS
ParameterType
defaults{ environment: string, isJsDev: boolean }

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.

Returns:
void

setGlobalAttributes(attributes)

Android
iOS
tvOS
ParameterType
attributes(optional)ObserveAttributes | null

Sets attributes merged into every subsequent metric and log event. Per-record keys win on collision. Pass null, undefined, or an empty object to clear.

Returns:
void

Example

Observe.setGlobalAttributes({ subscription_tier: 'pro', experiment_variant: 'B', });

Types

LogAttributeValue

Android
iOS
tvOS

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:

PropertyTypeDescription
key(index signature)LogAttributeValue
-

LogEventOptions

Android
iOS
tvOS

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.

PropertyTypeDescription
attributes(optional)Record<string, LogAttributeValue> | null

Custom attributes attached to the event. Each entry is preserved with its original value type — see LogAttributeValue for the supported shapes.

body(optional)string | null

Optional free-form message describing the event.

severity(optional)LogSeverity | null

Severity of the event.

Default:"info"

LogSeverity

Android
iOS
tvOS

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'

MetricAttributes

Android
iOS
tvOS
PropertyTypeDescription
params(optional)Record<string, unknown>

Custom parameters to attach to the metric.

routeName(optional)string | null

Name of the route associated with the metric. Some metrics populate this with a sensible default when omitted — for example, the TTI metric falls back to the initial route name detected from the router.

ObserveAttribute

Android
iOS
tvOS

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.

ObserveAttributes

Android
iOS
tvOS

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.

ObserveConfig

Android
iOS
tvOS
PropertyTypeDescription
dispatchInDebug(optional)boolean

Whether to dispatch metrics that were collected in a debug build of the host app.

When false, metrics produced by debug builds are marked as sent without being dispatched. When true, debug-build metrics are dispatched alongside release-build metrics.

Has no effect on release builds.

If dispatchingEnabled is false or this device is out-of-sample for sampleRate, nothing is dispatched regardless of dispatchInDebug.

Default:false
dispatchingEnabled(optional)boolean

Whether to dispatch observability events to the server.

When false, any pending metrics are marked as sent without being dispatched and no further metrics are dispatched until this is set back to true.

Default:true
environment(optional)string

The environment for observability events

Default:process.env.NODE_ENV
integrations(optional)ObserveIntegrationsConfig

Opt in to per-integration behavior. See the Expo Router and React Navigation integrations, or integrate your own package.

sampleRate(optional)number

Fraction of installations that should dispatch metrics, in [0, 1]. Values outside that range are clamped.

The decision is deterministic per installation — a device is either permanently in-sample or out-of-sample for a given rate, so the choice is stable across app launches.

Interaction with dispatchingEnabled:

  • If dispatchingEnabled is false, metrics are never dispatched
  • If dispatchingEnabled is true (or unset), metrics are dispatched only when this device is in-sample.
Default:undefined - metrics from all devices are sent

ObserveIntegrationsConfig

Android
iOS
tvOS
PropertyTypeDescription
expo-router(optional)boolean

Enables the expo-router integration, which records navigation metrics (cold_ttr, warm_ttr, tti) from router state changes.

Requires expo-router to be installed.

Default:false
react-navigation(optional)boolean

Enables the @react-navigation/native integration, which records navigation metrics (cold_ttr, warm_ttr, tti).

Requires @react-navigation/native to be installed and the app tree to be wrapped in <ObserveNavigationContainer> instead of the stock <NavigationContainer>.

Default:false