OpenTelemetry and OTLP
Creating custom spans with the OpenTelemetry JS API through @sophonz/react-native-tracer-provider — setup, context, span context, platform limits — and sending the same telemetry to another backend with @sophonz/react-native-otlp.
@sophonz/react-native-tracer-provider implements the OpenTelemetry TracerProvider interface over the native SDKs. You write spans with the standard @opentelemetry/api; the native SDK records them in the current session, next to crashes, network requests and logs. @sophonz/react-native-otlp goes the other way: it adds OTLP/HTTP exporters to the native SDKs, so everything they record also reaches a second backend.
Install
npm install @sophonz/react-native-tracer-provider@0.1.0 @opentelemetry/api
cd ios && pod install@opentelemetry/api ^1.9.0 comes with the package; add it to your own dependencies too, so your code and the provider share one copy. The package has native code, so rebuild the app.
Set up the provider
The provider needs a running SDK. The hook waits for it:
import {useEffect} from "react";
import {trace} from "@opentelemetry/api";
import {useSophonz} from "@sophonz/react-native";
import {useSophonzNativeTracerProvider} from "@sophonz/react-native-tracer-provider";
const SOPHONZ_CONFIG = {trackUnhandledRejections: true};
export default function App() {
const {isStarted} = useSophonz(SOPHONZ_CONFIG);
const {tracerProvider, tracer, isError, error} = useSophonzNativeTracerProvider(undefined, isStarted);
useEffect(() => {
if (tracerProvider) {
trace.setGlobalTracerProvider(tracerProvider);
}
}, [tracerProvider]);
// ...
}useSophonzNativeTracerProvider(config?, enabled = true) does nothing while enabled is false. Once enabled it checks that the native SDK is running and creates the provider. It returns:
| Field | Description |
|---|---|
tracerProvider | The provider, or null until ready |
tracer | A tracer named sophonz-default-tracer, or null |
isLoading | true until the check has finished |
isError, error | Set when @sophonz/react-native is missing or the SDK is not started. The error is also printed with console.warn |
Without React, create it directly after initialize has resolved:
import {trace} from "@opentelemetry/api";
import {initialize} from "@sophonz/react-native";
import {SophonzNativeTracerProvider} from "@sophonz/react-native-tracer-provider";
await initialize();
trace.setGlobalTracerProvider(new SophonzNativeTracerProvider());The constructor does not check that the SDK is running.
Registering globally
trace.setGlobalTracerProvider lets any module call trace.getTracer(name) without the provider being passed around, and lets OpenTelemetry-based libraries that call trace.getTracer record through Sophonz. Register once; the OpenTelemetry API ignores a second registration.
Custom spans
import {SpanStatusCode, trace} from "@opentelemetry/api";
const tracer = trace.getTracer("catalog", "2.3.0");
export async function loadCatalog(categoryId: string) {
const span = tracer.startSpan("load-catalog", {
attributes: {"catalog.category": categoryId},
});
try {
const items = await api.catalog(categoryId);
span.setAttribute("catalog.items", items.length);
span.addEvent("catalog-rendered");
return items;
} catch (e) {
span.recordException(e as Error);
span.setStatus({code: SpanStatusCode.ERROR, message: "catalog failed"});
throw e;
} finally {
span.end();
}
}| Span method | Recorded |
|---|---|
setAttribute, setAttributes | Yes. Strings, numbers, booleans; arrays are stringified on iOS |
addEvent(name, attributes?, time?) | Yes |
recordException(exception, time?) | An exception event with exception.type, exception.message, exception.stacktrace |
setStatus | Yes. On iOS an ERROR message is kept as otel.status_description |
end(time?) | Yes |
updateName | Android only |
addLink, addLinks | Passed to the native SDK, with a console warning that links are not fully supported |
startSpan options startTime, attributes, root | Yes |
startSpan option kind | Android only; iOS records every span as internal |
Times may be epoch milliseconds, Date or HrTime.
Helpers
| Helper | Description |
|---|---|
recordCompletedSpan(tracer, name, {parent?, attributes?, events?, status?, startTime?, endTime?, kind?, links?}) | Starts and ends a span in one call. For work you measured yourself |
asParent(span) | A context with span as the active span, for tracer.startSpan(name, options, asParent(span)) |
endAsFailed(span) | Sets ERROR status and ends |
startView(tracer, name) | A span named spz-screen-view with view.name and spz.type: ux.view. The navigation package does this for you |
import {recordCompletedSpan} from "@sophonz/react-native-tracer-provider";
recordCompletedSpan(tracer, "image-decode", {
startTime: decodeStartedAt,
endTime: Date.now(),
attributes: {"image.bytes": bytes},
});spz.type
A spz.type attribute classifies the span in the portal, as described in Android instrumentation. Spans without it default to perf. On iOS the attribute becomes the span's type rather than a plain attribute.
Context
The provider keeps the active context in JavaScript, on a stack that follows synchronous calls only. Two things follow from that.
Parent across await explicitly. startActiveSpan makes the span active for the synchronous part of the callback. After the first await, a tracer.startSpan call no longer sees it as the parent. Pass the parent instead:
import {asParent} from "@sophonz/react-native-tracer-provider";
const checkout = tracer.startSpan("checkout");
await validateCart();
const payment = tracer.startSpan("payment", {}, asParent(checkout));
await pay();
payment.end();
checkout.end();The global context manager. When config is omitted, the provider also registers its context manager with @opentelemetry/api, so context.active() and trace.getActiveSpan() work outside the tracer. Passing any config object, even {}, turns that off unless it includes setGlobalContextManager: true.
useSophonzNativeTracerProvider({setGlobalContextManager: true, spanContextSyncBehaviour: "throw"}, isStarted);Span context
Span ids are assigned by the native SDK, and the bridge is asynchronous. Right after startSpan, before the native side has answered, span.spanContext() has nothing to return.
spanContextSyncBehaviour | span.spanContext() before the answer |
|---|---|
"return_empty" (default) | Empty trace and span ids |
"throw" | Throws |
Wait for it when you need the ids, for example to build a traceparent header:
import type {SophonzNativeSpan} from "@sophonz/react-native-tracer-provider";
const {traceId, spanId} = await (span as SophonzNativeSpan).spanContextAsync();Limits
- A span that ended in an earlier session cannot be a parent: completed spans are released when the app moves between foreground and background, and a child started afterwards has no parent id.
- On iOS, the tracer's name, version and schema URL are not recorded,
kindandupdateNameare ignored, and array attribute values become strings. These follow from the Apple SDK's public API, which has no OpenTelemetryTracerProvider. - Spans are recorded by the native SDK, so they are exported with its batches and appear once the session uploads — on iOS, when the app goes to the background.
Additional OTLP exporters
@sophonz/react-native-otlp starts the native SDKs with OTLP/HTTP trace and log exporters next to the Sophonz collector. Everything the SDK records — native capture, JavaScript logs, spans from the tracer provider — is exported to both. Delivery to the Sophonz collector is unaffected.
npm install @sophonz/react-native-otlp@0.1.0
cd ios && pod installWhen JavaScript starts the SDK
Pass exporters to initialize or useSophonz. When exporters are present, the core package starts the SDK through the OTLP package instead of its own start.
import {initialize} from "@sophonz/react-native";
await initialize({
sdkConfig: {
ios: {
collectorUrl: "https://in.sophonz.ai",
appKey: "sk_ios_replace_me",
disabledUrlPatterns: ["otlp.example.com"],
},
exporters: {
traceExporter: {
endpoint: "https://otlp.example.com/v1/traces",
headers: [{key: "Authorization", token: "Bearer <token>"}],
timeout: 30,
},
logExporter: {
endpoint: "https://otlp.example.com/v1/logs",
headers: [{key: "Authorization", token: "Bearer <token>"}],
},
},
},
});| Field | Description |
|---|---|
endpoint | Full URL, including /v1/traces or /v1/logs. Required for each exporter you pass |
headers | {key, token} pairs sent with every export. token is the whole header value |
timeout | Seconds. The OpenTelemetry exporter default applies when omitted |
Either exporter may be left out.
CAUTION — An invalid exporter block stops the start
When exporters is not an object, or an exporter has no string endpoint, or its headers is not an array, the OTLP package prints [Sophonz] Invalid ... and the SDK is not started at all: initialize resolves false. Check the console after changing exporter settings.
On iOS, exporters with no collectorUrl/appKey and no Sophonz-Info.plist start the SDK in exporter-only mode, sending nothing to Sophonz. On Android the Sophonz collector from sophonz-config.json is always used as well.
Metro must allow require.context
The core package finds the OTLP package with Metro's require.context, so that apps without it do not fail to bundle. Expo enables that. A bare React Native app must enable it in metro.config.js:
const {getDefaultConfig, mergeConfig} = require("@react-native/metro-config");
module.exports = mergeConfig(getDefaultConfig(__dirname), {
transformer: {
unstable_allowRequireContext: true,
},
});Without it the console shows an error ocurred when checking if @sophonz/react-native-otlp was installed, the SDK starts without exporters, and initialize still resolves true. The lookup expects both packages side by side in node_modules/@sophonz, which is the layout npm and Yarn produce; a layout that nests one package inside the other breaks it the same way.
Keep exports out of network capture
Both SDKs capture HTTP requests, including the exporter's own. Left alone, each export produces a network span that is exported in turn. The SDKs exclude their own collector automatically, but not a second backend.
- Android: add the host to
sdk_config.networking.disabled_url_patternsinsophonz-config.json. - iOS: add it to
sdkConfig.ios.disabledUrlPatterns, or toURLSessionCaptureService.Options(ignoredURLs:)when starting natively.
When the SDK starts natively
With the Expo plugin, the wizard, or your own native start, exporters in JavaScript is ignored. Register the exporters in native code, before start. The OTLP package already brings the exporter libraries into the app.
import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter
import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter
import io.sophonz.android.sophonzsdk.Sophonz
import io.sophonz.android.sophonzsdk.otel.java.addJavaLogRecordExporter
import io.sophonz.android.sophonzsdk.otel.java.addJavaSpanExporter
override fun onCreate() {
super.onCreate()
Sophonz.addJavaSpanExporter(
OtlpHttpSpanExporter.builder()
.setEndpoint("https://otlp.example.com/v1/traces")
.addHeader("Authorization", "Bearer <token>")
.build()
)
Sophonz.addJavaLogRecordExporter(
OtlpHttpLogRecordExporter.builder()
.setEndpoint("https://otlp.example.com/v1/logs")
.addHeader("Authorization", "Bearer <token>")
.build()
)
Sophonz.start(this)
// ...
}import Foundation
import OpenTelemetryProtocolExporterHttp
import SophonzIO
@objcMembers class SophonzInitializer: NSObject {
static func start() {
let otel = Sophonz.OTelOptions(
spanExporters: [OtlpHttpTraceExporter(endpoint: URL(string: "https://otlp.example.com/v1/traces")!)],
logExporters: [OtlpHttpLogExporter(endpoint: URL(string: "https://otlp.example.com/v1/logs")!)]
)
do {
try Sophonz.start(
options: .withCollector(
url: "https://in.sophonz.ai",
appKey: "sk_ios_replace_me",
platform: .reactNative,
otel: otel
)
)
} catch {
print("[sophonz] failed to start: \(error)")
}
}
}After editing SophonzInitializer.swift in an Expo app, avoid npx expo prebuild --clean, which regenerates it, or keep the change in a config plugin of your own.