Skip to content
Last9
Book demo

Android / Kotlin

Install and configure the Last9 Android RUM SDK. Kotlin API, CDN-hosted Maven AAR, automatic instrumentation for sessions, views, OkHttp, errors, ANRs, and resource sampling.

Real User Monitoring for Android apps. Automatic instrumentation for sessions, views, network requests, errors, ANR detection, and resource metrics via OpenTelemetry.

Prerequisites

  • Android minSdk 21 (Android 5.0+)
  • Kotlin 1.9.0+ and Android Gradle Plugin 8.3.0+
  • An Application subclass
  • A Last9 RUM client token and OTLP endpoint

Create a Client Monitoring Token

  1. Open Last9 → Settings → Ingestion Tokens
  2. Click Create Token → choose type Client
  3. Set the allowed origin to android://com.yourcompany.yourapp — use your app’s exact package name
  4. Copy the token and the OTLP endpoint URL

CDN artifacts

ArtifactStable URLVersioned URL
POMhttps://cdn.last9.io/rum-sdk/android/builds/stable/v1/rum-android.pomhttps://cdn.last9.io/rum-sdk/android/maven/io/last9/rum-android/1.14.0/rum-android-1.14.0.pom
AARhttps://cdn.last9.io/rum-sdk/android/builds/stable/v1/rum-android.aarhttps://cdn.last9.io/rum-sdk/android/maven/io/last9/rum-android/1.14.0/rum-android-1.14.0.aar
Maven repo root—https://cdn.last9.io/rum-sdk/android/maven/

Maven coordinates for the latest versioned release: io.last9:rum-android:1.14.0. The major-pinned stable/v1 direct-download channel currently serves 1.8.0; staging builds use the -alpha suffix.

Installation

  1. Add the CDN Maven repository

    dependencyResolutionManagement {
    repositories {
    google()
    mavenCentral()
    maven { url = uri("https://cdn.last9.io/rum-sdk/android/maven/") }
    }
    }
  2. Add the dependency

    In your app’s build.gradle.kts:

    dependencies {
    // Pinned to an exact release (reproducible builds):
    implementation("io.last9:rum-android:1.14.0")
    // Or resolve the newest published 1.x release from the versioned Maven repo
    // (independent of the stable/v1 direct-download alias):
    // implementation("io.last9:rum-android:1.+")
    }
  3. Initialize the SDK

    In your Application subclass:

    import android.app.Application
    import io.last9.rum.L9Rum
    import io.last9.rum.L9RumConfig
    import io.last9.rum.L9BaggageConfig
    class MyApplication : Application() {
    override fun onCreate() {
    super.onCreate()
    L9Rum.initialize(
    this,
    L9RumConfig(
    baseUrl = "https://otlp-ext-aps1.last9.io/v1/otlp/organizations/<org>",
    // Use android://com.your.package.name — must match the
    // origin allowlist on your Last9 client token.
    origin = "android://com.example.myapp",
    clientToken = "your-client-token",
    serviceName = "my-android-app",
    serviceVersion = "1.0.0",
    deploymentEnvironment = "production",
    )
    )
    }
    }
  4. Register the Application class

    In AndroidManifest.xml:

    <application android:name=".MyApplication" ... >

Check the connection from code

From 1.14.0, call L9Rum.sendTestEvent(callback) after initialize to confirm that telemetry reaches Last9. The SDK sends one l9.test_event span at once (not in a batch) and calls the callback one time with the export result.

import android.util.Log
import io.last9.rum.L9Rum
L9Rum.sendTestEvent { result ->
if (result.ok) {
Log.i("App", "Last9 RUM is connected: ${result.status}")
} else {
Log.w("App", "Last9 RUM cannot reach Last9: ${result.status} ${result.error}")
}
}

The callback can run on a background thread. Switch to the main thread before you change the UI.

To monitor every export, set onExport (each trace export) or onError (each failed trace export) in L9RumConfig. These callbacks run on a background thread and do not depend on debugLogs.

import android.util.Log
import io.last9.rum.L9ExportCallback
import io.last9.rum.L9RumConfig
val config = L9RumConfig(
baseUrl = "https://otlp-ext-aps1.last9.io/v1/otlp/organizations/<org>",
origin = "android://com.example.myapp",
clientToken = "your-client-token",
serviceName = "my-android-app",
serviceVersion = "1.0.0",
deploymentEnvironment = "production",
onError = L9ExportCallback { result ->
// for example ok=false, status=400, spanCount=12,
// error="HTTP 400: token origin not allowed"
Log.w("App", "Last9 export failed: ${result.status} ${result.error}")
},
)

L9ExportResult has these fields:

FieldTypeDescription
okBooleantrue when Last9 accepted the export (HTTP 2xx)
statusIntHTTP status. 0 when there was no HTTP response (network error, timeout)
spanCountIntNumber of spans in the export
errorString?Failure reason, with the HTTP status and the Last9 response text when there is one. sendTestEvent also uses not_initialized, session_not_sampled, and timeout

sendTestEvent gives these errors when it cannot send the span or gets no result:

  • not_initialized: L9Rum.initialize did not run, or shutdown() ran. The SDK sends nothing.
  • session_not_sampled: the session is not sampled. The SDK sends nothing. Set sampleRate = 100 while you verify the setup.
  • timeout: no export result came back within exportTimeoutMs plus 5 seconds.

What’s captured automatically

SignalDetails
Network requestsOkHttp interceptor — latency, status code, URL
Screen viewsActivity lifecycle via ActivityLifecycleCallbacks
Sessions30m inactivity / 4h max, persisted across restarts. Home/background keeps the session (v1.4.1+)
App launch timeCold and warm start duration
Resource metricsMemory and CPU sampled periodically
View vitalsPer-view refresh rate, slow/frozen frames, and memory on each View span (v1.7.0+)
ErrorsUnhandled exceptions and JVM crashes
ANR detectionMain thread blocks beyond threshold (default 5s)
view.ttfdTime from last HTTP response to next rendered frame — measures post-API render latency on data-driven screens

View time-to-full-display (view.ttfd)

view.ttfd measures how long it takes for the screen to render after the last API response completes. It captures the delta between the HTTP response timestamp and the next Choreographer frame — giving you end-to-end visibility on data-driven screens where content appears only after a network call.

AttributeTypeDescription
view.ttfdfloatMilliseconds between HTTP response end and next rendered frame
view.ttidfloatMilliseconds from screen open to first frame (unchanged)

How it works: after any L9NetworkInterceptor span ends, the SDK schedules a Choreographer.FrameCallback. The callback fires on the next VSYNC, and the SDK records the delta as view.ttfd on the active View span.

  • Works on both Jetpack Compose and View-based UIs with no app code changes.
  • Applies to the View span that was active when the HTTP call was made.
  • If no View span is active when the response arrives, the measurement is skipped.

Per-view performance vitals (v1.7.0+)

When resourceMonitoringEnabled is on (the default), each View span carries per-view frame and memory vitals, so you can find which screens janked or ran hot without extra instrumentation.

AttributeTypeDescription
view.refresh_rate_averagefloatAverage refresh rate over the view, normalized to 0–60 Hz so 60 Hz and 120 Hz devices compare directly
view.refresh_rate_minfloatLowest refresh rate seen during the view (the worst dip)
view.frame.slowintSlow frames — inter-vsync interval above 1.5× the display refresh period (a skipped vsync)
view.frame.frozenintFrozen frames — longer than 700 ms
view.memory_averageintAverage resident-set-size (RSS) bytes over the view
view.memory_maxintPeak RSS bytes during the view
process.cpu.usagefloatProcess CPU usage averaged over the view’s lifetime
  • Frame timing comes from a Choreographer frame-rate tracker. Per-view memory is sampled (RSS) at each view start and end, so even short screens get coverage — alongside the periodic resource.sample span, which also carries process.memory.pss (proportional set size).
  • Frame tracking pauses while the app is backgrounded, so a background gap is never counted as a frozen frame.
  • Periodic resource.sample spans now carry view.id while a view is active, so process-level samples can be correlated to the screen that was active.
  • No API change: the vitals ride on the existing resourceMonitoringEnabled flag. Set it to false to turn off resource sampling and these vitals together.

Where to see it: open a session in the Last9 RUM UI, select a view on the timeline, and check the Attributes tab. Views that carry these attributes show a MOBILE VITALS section with rows such as Refresh Rate (avg), Slow Frames, Frozen Frames, Memory (avg), and CPU Usage, formatted with units. Web views are unaffected.

MOBILE VITALS section in the view Attributes tab

Configuration

import io.last9.rum.L9BaggageConfig
import io.last9.rum.L9ExportCallback
import io.last9.rum.L9GraphQLDetailConfig
import io.last9.rum.L9NetworkIgnorePatterns
import io.last9.rum.L9NetworkSpanNameRule
import io.last9.rum.L9PropagationMode
import io.last9.rum.L9RumConfig
import io.last9.rum.L9UrlPattern
val config = L9RumConfig(
// --- Required ---------------------------------------------------------
// OTLP collector endpoint
baseUrl = "https://otlp-ext-aps1.last9.io/v1/otlp/organizations/<org>",
// Authentication token from Last9
clientToken = "your-client-token",
// Application identifier (maps to service.name)
serviceName = "my-android-app",
// App version string (maps to service.version)
serviceVersion = "1.0.0",
// Environment name
deploymentEnvironment = "production",
// --- Optional ---------------------------------------------------------
// Required for client_monitoring tokens. Use android://com.your.package.name —
// must match the origin allowlist configured on your Last9 client token.
origin = "android://com.example.myapp",
// Specific build identifier (maps to app.build_id)
appBuildId = "1.0.0-build-42",
// Optional override for the app.installation.id resource attribute.
// The Client-ID header always uses the SDK-generated per-install UUID.
appInstallationId = null,
// Session sampling rate: 0-100 (percentage). 100 = sample everything.
sampleRate = 100,
// Print debug logs to logcat
debugLogs = false,
// Automatically trace HTTP requests via OkHttp interceptor
networkInstrumentation = true,
// Automatically capture unhandled exceptions
errorInstrumentation = true,
// Max spans per export batch
maxExportBatchSize = 100,
// How long batch processors wait before flushing queued spans/logs (ms).
// Unset: 5000 in production, 1000 when debugLogs is true (`v1.4.0+`).
scheduleDelayMs = null,
// When false, Activity resume/pause no longer opens or closes view spans —
// the app owns view names via startView / setViewName (`v1.5.0+`).
autoViewTrackingEnabled = true,
// Export timeout in milliseconds
exportTimeoutMs = 30_000L,
// Enable ANR (Application Not Responding) detection
anrDetectionEnabled = true,
// ANR threshold in milliseconds
anrThresholdMs = 5_000L,
// Periodically sample memory and CPU
resourceMonitoringEnabled = true,
// Interval between resource samples (ms)
resourceSamplingIntervalMs = 30_000L,
// Setting this to true will hide network requests (and their
// DNS/TCP/TLS/TTFB phase child spans) from the Last9 dashboard's
// Sessions → APIs tab. Each request would get its own traceId
// instead of sharing the current view's traceId, and that tab
// only fetches spans that share the View's traceId. Keep this
// false unless you specifically need per-request trace isolation.
isolateTracePerRequest = false,
// Custom resource attributes added to every span.
// telemetry.distro.name and telemetry.distro.version are SDK-owned:
// an entry here with the same key does not change them (`v1.10.0+`).
resourceAttributes = mapOf(
"app.platform" to "android",
),
// W3C Baggage propagation on outgoing requests
baggage = L9BaggageConfig(
enabled = false,
allowedKeys = listOf("session.id", "user.id"),
maxTotalBytes = 8192,
trackedUrlPatterns = emptyList(),
warnAtPercentage = 80,
),
// Substring patterns — matching URLs are skipped before span creation.
// Prefer ignorePatterns below for regex support and hostname/pathname targeting.
excludedUrlPatterns = listOf(".jpg", ".png", ".pdf", "cdn.example.com"),
// Fine-grained network ignore rules. Matched URLs are dropped before span
// creation. Strings use substring matching; L9UrlPattern.Regex uses regex
// search semantics. Takes precedence over excludedUrlPatterns.
ignorePatterns = L9NetworkIgnorePatterns(
fullUrl = listOf(
L9UrlPattern.Contains("https://cdn.example.com"),
L9UrlPattern.Regex("^https://.*\\.example\\.com", flags = "i"),
),
pathname = listOf(
L9UrlPattern.Contains(".pdf"),
L9UrlPattern.Contains(".jpg"),
L9UrlPattern.Regex("^/internal/metrics"),
),
hostname = listOf(
L9UrlPattern.Contains("cdn.example.com"),
L9UrlPattern.Regex("(^|\\.)assets\\.example\\.com$", flags = "i"),
),
),
// Trace header propagation for ignored URLs.
// PRESERVE (default): keep traceparent on ignored requests so downstream
// services retain trace context.
// STRIP: remove traceparent from ignored requests (e.g. third-party CDNs).
propagationMode = L9PropagationMode.PRESERVE,
// Rename path parts in the default network span name, in list order,
// before the numeric/UUID folding. url.full keeps the real URL.
// networkSpanHook wins over these rules (`v1.9.0+`).
networkSpanNameRules = listOf(
L9NetworkSpanNameRule(L9UrlPattern.Regex("^/shop/[^/]+/"), "/shop/{shop}/"),
),
// Opt-in GraphQL variable and error detail. Off by default (`v1.12.0+`).
graphqlDetail = L9GraphQLDetailConfig(
captureVariables = false,
variableAllowList = emptyList(),
extraSensitivePatterns = emptyList(),
maxVariables = 10,
maxVariableValueLength = 256,
captureErrorDetails = false,
maxErrors = 5,
maxErrorFieldLength = 200,
),
// Called after each trace export, on a background thread.
// Not gated by debugLogs (`v1.14.0+`).
onExport = null,
// Called after each failed trace export, on a background thread.
// Not gated by debugLogs (`v1.14.0+`).
onError = L9ExportCallback { result ->
android.util.Log.w("App", "Last9 export failed: ${result.error}")
},
)

Per-install Client-ID

Starting with 0.8.0, the Client-ID ingestion header is an SDK-generated per-install UUID, not serviceName. The UUID is generated on first launch and stored in Context.getNoBackupFilesDir(), which is excluded from Android Auto Backup. This keeps each device in its own ingestion rate-limit bucket.

appInstallationId only overrides the app.installation.id resource attribute. It does not override the Client-ID header, so the header and the resource attribute can differ when you set appInstallationId manually.

Telemetry distro attributes

From 1.10.0, the trace and log resource carries telemetry.distro.name and telemetry.distro.version. These attributes identify the Last9 RUM package that sent the telemetry.

Integrationtelemetry.distro.nametelemetry.distro.version
Android SDK directlylast9-rum-androidAndroid SDK version
React Native wrapper starts the SDKlast9-rum-react-nativeReact Native SDK version
Flutter wrapper starts the SDKlast9-rum-flutterFlutter SDK version
  • The SDK owns these values. A resourceAttributes entry with the same key does not change them.
  • telemetry.sdk.* and service.version do not change. There is no new configuration option.

API reference

Identify a user

L9Rum.identify("user-123", mapOf(
"email" to "user@example.com",
"plan" to "premium",
))

Clear user on sign-out

L9Rum.clearUser()

Capture errors

try {
// risky operation
} catch (e: Exception) {
L9Rum.captureError(e, mapOf("screen" to "checkout"))
}

Unhandled exceptions are captured automatically when errorInstrumentation = true.

Track views

Activities are tracked automatically via ActivityLifecycleCallbacks. Use the manual API for fragments or Compose destinations:

L9Rum.startView("ProductDetailsScreen")
L9Rum.setViewName("Product #42")

From 1.5.0, startView ends whichever native view is currently open before opening a new one, so mixing a manual startView with Activity auto-tracking no longer leaves a duplicate native view. setViewName renames the active view in place with no extra span — the recommended way to name a WebView host Activity alongside instrument(webView). From 1.6.0, instrumented WebView host views are also auto-named from the folded URL pathname (view.url holds the full URL); setViewName still wins. Set autoViewTrackingEnabled = false when the app owns all view names.

Custom events

L9Rum.addEvent("purchase_completed", mapOf(
"product_id" to "12345",
"amount" to 29.99,
))

Each call dual-emits:

  • A span event on the active view span, so the event shows up on the view’s timeline in RUM.
  • An OTLP log record carrying event.type=custom, event.name, your attributes, and session.id/user attributes. When a view is active the log is correlated to it via trace.id/span.id/view.id, so you can pivot between the log and the RUM session.

Log emission is unconditional. If no view is active when you call addEvent, the span event is dropped (no view is fabricated to attach it to) but the log is still sent as an orphan, omitting trace.id/span.id/view.id. A custom event never silently vanishes because it fired outside a view.

From 1.5.2, an addEvent fired while a screen is being torn down attaches to that screen (a 1000 ms grace window after the view ends), not the next one. After the window, and whenever no view is current, the OTLP log still correlates to the last view for the rest of the session. A manual startView(...) ends the previous view immediately. Prefer firing screen summaries in onPause (Activity) / onDestroyView or onPause (Fragment) rather than onDestroy.

Custom spans

From 1.11.0, time your own operations with L9Rum. You do not need your own OpenTelemetry tracer.

import io.last9.rum.L9Rum
import io.opentelemetry.api.trace.SpanKind
// A finished span: ends now, started 250 ms ago
L9Rum.recordSpan("checkout.validate", durationMs = 250, attributes = mapOf("items" to 3))
// Or with explicit epoch-ms times
val t0 = System.currentTimeMillis()
// ... work
val t1 = System.currentTimeMillis()
L9Rum.recordSpan("cache.sync", startTimeMs = t0, endTimeMs = t1, kind = SpanKind.CLIENT)
// A span you end yourself
val handle: String? = L9Rum.startSpan("image.decode", mapOf("format" to "webp"))
// ... later
handle?.let { L9Rum.endSpan(it) }
MethodReturns
recordSpan(name, durationMs = null, startTimeMs = null, endTimeMs = null, attributes = emptyMap(), kind = SpanKind.INTERNAL)Boolean
startSpan(name, attributes = emptyMap(), kind = SpanKind.INTERNAL)String?
endSpan(handle)Unit
  • A custom span is a child of the active view span and carries view.id and l9.span.category=custom, so it shows under the view. With no view open, it is a root span.
  • recordSpan takes either durationMs or startTimeMs + endTimeMs. Both forms, neither, a partial pair, a negative duration, or end < start emit nothing and return false.
  • kind is SpanKind.INTERNAL by default, so custom spans feed the trace_internal_* metrics. Pass another SpanKind to change it.
  • Attributes keep String, Boolean, Int / Long, finite Float / Double, and lists of String. The SDK drops other value types, NaN, and infinities. It does not convert them to strings. At most 64 of your attributes are kept, chosen by sorted key. Session, user, and global attributes are added as for any other span.
  • A span that is not ended within 5 minutes is ended with ERROR status. shutdown() ends all open spans.
  • endSpan with an unknown or already-ended handle does nothing.
  • Before initialize, or with a blank name, recordSpan returns false and startSpan returns null.
  • addEvent does not change.

Global span attributes

// Inject attributes into every span
L9Rum.spanAttributes(mapOf(
"experiment" to "checkout_v2",
"feature_flag" to "new_cart",
))
// Clear
L9Rum.spanAttributes(null)

A Java map with null keys or null values does not throw a NullPointerException. The SDK drops the null entries and applies the valid entries in the same map.

Network phase child spans

When OkHttp instrumentation is enabled, each parent HTTP span includes child spans for individual network phases:

Child spanWhat it measures
dnsDNS lookup duration
tcp_connectTCP connection establishment
tls_handshakeTLS negotiation
ttfbTime from request sent to first response byte

No SDK config change is required — phase spans are emitted automatically.

Reused connections skip DNS, TCP, and TLS work. From 1.11.2, the SDK omits each DNS, TCP, TLS, or TTFB phase that it did not observe. Before 1.11.2, the SDK emitted zero-duration child spans with l9rum.network.phase.skipped=true for these phases.

Network interceptor (manual OkHttp setup)

When networkInstrumentation = true, HTTP calls through the SDK’s default client are traced automatically including network phase child spans. For a custom OkHttpClient, use L9Rum.instrumentOkHttp(builder, context) to attach both the HTTP span interceptor and the OkHttp EventListener.Factory required for phase timings:

val client = OkHttpClient.Builder()
.let { L9Rum.instrumentOkHttp(it, context) }
.build()

If you use SSL pinning:

val client = OkHttpClient.Builder()
.certificatePinner(existingPinner) // SSL pinning unchanged
.let { L9Rum.instrumentOkHttp(it, context) }
.build()

instrumentOkHttp binds the tracer that is current when you call it. If you cache an instrumented client and then call shutdown() and initialize() again, the cached client still reports through the old tracer. From 1.11.2, use L9Rum.currentOkHttpTracerIdentity() to find out when to build the client again. It returns an opaque identity of the tracer that instrumentOkHttp binds now, or null when it binds none (the SDK is not initialized, or network instrumentation is off).

import android.content.Context
import io.last9.rum.L9Rum
import okhttp3.OkHttpClient
object ApiClient {
private var client: OkHttpClient? = null
private var tracerIdentity: Any? = null
@Synchronized
fun get(context: Context): OkHttpClient {
val identity = L9Rum.currentOkHttpTracerIdentity()
val cached = client
if (cached != null && identity === tracerIdentity) return cached
val rebuilt = L9Rum.instrumentOkHttp(OkHttpClient.Builder(), context).build()
client = rebuilt
tracerIdentity = identity
return rebuilt
}
}

From 1.9.0, OkHttp network spans also carry the legacy http.method, http.url, and http.status_code attributes, as spans from startNetworkSpan / endNetworkSpan already did. Span-derived metrics read http.status_code for the http_status_code label. Before 1.9.0, OkHttp requests did not show in the RUM Network endpoint view. The stable http.request.method, url.full, and http.response.status_code attributes do not change.

GraphQL network observability

When OkHttp instrumentation is enabled, GraphQL requests are enriched automatically — the SDK parses the operation name and type from JSON request bodies and /graphql paths. No extra configuration is required.

Span attributeExampleNotes
Span nameGraphQL: "GetUserPreferences" queryRenamed to a descriptive name
graphql.operation.nameGetUserPreferencesOperation name parsed from the request body
graphql.operation.typequeryquery, mutation, or subscription
l9.span.categorynetworkCategorizes the span for dashboard filtering

GraphQL servers often return errors with an HTTP 200 status and an errors[] array in the response body. The SDK detects these and marks the span as an error:

Span attributeValueNotes
error.typeGraphQLErrorSet when the response contains a non-empty errors[]
graphql.error.countnumberNumber of entries in the errors[] array

From 1.13.0, the SDK also supports these GraphQL transports:

  • Batches: a JSON array of operations makes one network span. A batch of more than one operation is named GraphQL: batch and gets graphql.batch.size (total operation count) and graphql.batch.operation.names (unique names in request order, max 10; anonymous operations are not included). A batch of one operation is named like that operation and gets graphql.batch.size=1. Different batches share the GraphQL: batch row; open a trace to see its operation names.
  • Persisted queries: a request with extensions.persistedQuery (for example Apollo APQ) gets graphql.persisted_query=true and graphql.persisted_query.id (the sha256Hash, when it matches ^[A-Za-z0-9_-]{1,128}$). The hash is never part of the span name. A request with only the hash keeps the name {METHOD} graphql.
  • GET: a GET to a path that contains graphql is parsed from the query string (query, operationName, extensions). The SDK never reads variables from the URL.
  • Multipart responses (@defer, @stream, multipart subscriptions): graphql.error.count adds the errors in errors[], incremental[].errors, completed[].errors, and subscription payload errors across all parts. A batch response adds the errors of all its elements. OkHttp sends a multipart/* response to your app at once. The SDK keeps the first 64 KiB while your app reads the body, and ends the span when the stream ends or the body is closed.

A JSON body is GraphQL only when it has a non-empty string operationName, a non-empty string query, or extensions.persistedQuery.

GraphQL detail (opt-in)

To debug a GraphQL request, you can export selected variables and the GraphQL error detail. Both are off by default. From 1.12.0, set them with graphqlDetail in L9RumConfig. The field names are the same in the Web, iOS, React Native, and Flutter SDKs.

import io.last9.rum.L9GraphQLDetailConfig
import io.last9.rum.L9RumConfig
val config = L9RumConfig(
baseUrl = "https://otlp-ext-aps1.last9.io/v1/otlp/organizations/<org>",
origin = "android://com.example.myapp",
clientToken = "your-client-token",
serviceName = "my-android-app",
serviceVersion = "1.0.0",
deploymentEnvironment = "production",
graphqlDetail = L9GraphQLDetailConfig(
captureVariables = true,
variableAllowList = listOf("tenantId", "input.page.limit", "items.0.id"),
extraSensitivePatterns = listOf("email"),
captureErrorDetails = true,
),
)
OptionTypeDefaultDescription
captureVariablesBooleanfalseExport the allow-listed variables
variableAllowListList<String>emptyList()Dot paths to leaf values (tenantId, input.page.limit, items.0.id)
extraSensitivePatternsList<String>emptyList()Extra key patterns to redact, added to the built-in list
maxVariablesInt10Max graphql.variables.* attributes per span
maxVariableValueLengthInt256Max characters per variable value
captureErrorDetailsBooleanfalseExport per-error detail
maxErrorsInt5Max errors (by index) that get detail attributes
maxErrorFieldLengthInt200Max characters of each error field

A limit that is zero or less uses its default.

Span attributeSource
graphql.variables.<entry>The scalar value at the allow-list entry
graphql.error.<i>.messageerrors[i].message
graphql.error.<i>.codeerrors[i].extensions.code
graphql.error.<i>.patherrors[i].path, joined with . (for example user.0.name)
graphql.error.<i>.locationserrors[i].locations as line:column, joined with ,
exception.messageThe first captured graphql.error.<i>.message
  • Only string, number, and boolean values are exported. Object, array, and null values are never exported, even when their path is allow-listed.
  • A value is exported as [REDACTED] when any segment of its path contains a sensitive pattern (case-insensitive): password, passwd, secret, token, apikey, api_key, api-key, authorization, credential, cookie, plus extraSensitivePatterns.
  • Error extensions other than code and the response data are never read.
  • The detail applies to the OkHttp interceptor and to L9Rum.startNetworkSpan / L9Rum.endNetworkSpan (React Native and Flutter bridges). On the bridge, a transport errorMessage wins over the GraphQL error message for exception.message.

For cross-cutting customization of any network span (GraphQL or REST), set networkSpanHook on L9RumConfig to inspect and enrich spans before they are exported.

From 1.3.0, REST network span names fold fully-numeric and UUID path segments to ? (for example GET /workspaces/1 becomes GET /workspaces/?). Version-like segments such as v2 are preserved. GraphQL span names are unaffected. The raw URL remains on url.full. A spanNameOverride or networkSpanHook still overrides the folded name.

Network span name rules

From 1.9.0, set networkSpanNameRules in L9RumConfig to rename parts of the request path in the default network span name. Use it for dynamic path segments that the numeric and UUID folding does not catch, for example slugs or short IDs.

import io.last9.rum.L9NetworkSpanNameRule
import io.last9.rum.L9RumConfig
import io.last9.rum.L9UrlPattern
val config = L9RumConfig(
baseUrl = "https://otlp-ext-aps1.last9.io/v1/otlp/organizations/<org>",
origin = "android://com.example.myapp",
clientToken = "your-client-token",
serviceName = "my-android-app",
serviceVersion = "1.0.0",
deploymentEnvironment = "production",
networkSpanNameRules = listOf(
// GET /shop/acme-store/cart -> GET /shop/{shop}/cart
L9NetworkSpanNameRule(L9UrlPattern.Regex("^/shop/[^/]+/"), "/shop/{shop}/"),
// GET /orders/ord_8f2k/items -> GET /orders/{id}/items
// GET /invoices/inv_x7p2 -> GET /invoices/{id}
// "\$1" is the first regex group ("\$" is a literal $ in a Kotlin string).
L9NetworkSpanNameRule(L9UrlPattern.Regex("/(orders|invoices)/[a-z]+_[A-Za-z0-9]+"), "/\$1/{id}"),
// Literal replacement
L9NetworkSpanNameRule(L9UrlPattern.Contains("/legacy-api/"), "/api/"),
),
)
  • L9NetworkSpanNameRule(match, replacement) replaces every match in the request path.
  • L9UrlPattern.Contains replaces the literal value. L9UrlPattern.Regex replaces every regex match, and replacement can use $1-style group references.
  • The SDK applies the rules in list order, then folds numeric and UUID segments to ?.
  • The rules apply to OkHttp spans and to L9Rum.startNetworkSpan. The request URL and url.full do not change. GraphQL span names do not change.

The SDK selects the span name in this order:

  1. spanName on L9Rum.startNetworkSpan (React Native and Flutter bridges)
  2. The span name from networkSpanHook
  3. The default name: {METHOD} {path} after networkSpanNameRules and folding, or the GraphQL name

From 1.9.0, L9Rum.startNetworkSpan accepts an optional spanName. The React Native and Flutter SDKs use it to apply a JavaScript or Dart span name hook across the bridge.

Network connectivity attributes

HTTP spans are annotated with the device’s network conditions — connection type (wifi, cell, etc.), cellular subtype, and carrier name when available.

The SDK does not require the READ_PHONE_STATE permission. Without it (the common case), the connection is still reported as cell and the network.connection.subtype attribute is simply omitted. Telemetry attribute collection is fully isolated from the request path, so a permission check can never fail an otherwise-successful HTTP request.

Session ID

val sessionId: String? = L9Rum.getSessionId()

Session start is synchronous, so getSessionId() returns the active session id as soon as initialize() returns. From 1.1.9, it returns null (never an empty string) when there is no active session, and addSessionIdObserver’s initial callback reports the same value — both read through one accessor, so an internal placeholder id is never surfaced to callers.

From 1.4.1, backgrounding the app (Home button or a system file picker) no longer ends the RUM session. Returning within the 30-minute inactivity window resumes the same session, so later events keep their session.id. Rollover still happens on inactivity timeout, max duration, or shutdown(). A force-quit, crash, or OS kill backfills Session End on the next cold start — backdated to last activity, with session.end_reason=process_death — then starts a fresh session chained via session.previous_id. A same-process re-init (for example a React Native JS reload) still restores the in-window session.

Every span carries session.start_time (epoch ms) alongside session.id, so the backend can read the real start time of a session from any span. The Session Start, Session End, and process-death tombstone spans carry the start time of the session they belong to. When a session rolls over on inactivity timeout or max duration, Session End and session.time_spent use the last recorded activity, so idle and background time is not counted, and the new session keeps session.previous_id. exit, shutdown, and process_death ends are unchanged.

Flush pending data

L9Rum.flush()

Call flush() before the app exits or in response to critical lifecycle events where losing the last batch matters.

Embedded per-flow lifecycle

For embedded integrations scoped to a single flow (for example, RUM that should only run while a specific feature or mini-app is open), use shutdown() and isActive() to control the SDK lifecycle:

// Scope RUM to a single flow, then tear it down so the next flow starts clean.
L9Rum.initialize(application, config)
// Attributes known only after the flow starts apply to every later span,
// and are cleared on shutdown().
L9Rum.spanAttributes(mapOf("tenant.id" to "acme", "feature.flag" to "beta"))
if (L9Rum.isActive()) {
L9Rum.shutdown() // flush + full teardown; a later initialize() re-arms RUM
}
  • shutdown() flushes pending spans and fully tears RUM down. It ends the active view and emits the session-end span before flushing, so short per-flow sessions export cleanly. Activity lifecycle callbacks are unregistered and the previous uncaught-exception handler is restored. If another crash reporter installed its handler after Last9, shutdown() keeps that reporter installed and does not restore the older handler.
  • isActive() reports whether RUM is currently running.
  • After shutdown(), calling initialize() again starts a fresh flow (supported re-init cycle).

Network ignore patterns

Skip noisy URLs before span creation by matching against full URL, pathname, or hostname. Strings use substring matching; L9UrlPattern.Regex uses regex search semantics.

import io.last9.rum.L9NetworkIgnorePatterns
import io.last9.rum.L9UrlPattern
L9Rum.initialize(
this,
L9RumConfig(
// ...required config
ignorePatterns = L9NetworkIgnorePatterns(
fullUrl = listOf(
L9UrlPattern.Contains("https://cdn.example.com"),
L9UrlPattern.Regex("^https://.*\\.example\\.com", flags = "i"),
),
pathname = listOf(
L9UrlPattern.Contains(".pdf"),
L9UrlPattern.Contains(".jpg"),
L9UrlPattern.Regex("^/internal/metrics"),
),
hostname = listOf(
L9UrlPattern.Contains("cdn.example.com"),
L9UrlPattern.Regex("(^|\\.)assets\\.example\\.com$", flags = "i"),
),
),
// PRESERVE (default): keep traceparent on ignored requests.
// STRIP: remove traceparent from ignored requests.
propagationMode = L9PropagationMode.PRESERVE,
),
)

WebView correlation

Inject the active native session and view IDs into a WebView so Browser RUM spans share the same session.id:

// After inflating the WebView — call once per WebView instance.
L9Rum.instrument(webView)
// Set a friendly name on the auto-tracked native host view.
// Do NOT call startView() here — Activity lifecycle already tracks the screen.
L9Rum.setViewName("WebViewActivity")
  • Native context is re-injected on every session or view rollover via evaluateJavascript.
  • Browser RUM spans that adopt the native session.id do not carry session.start_time. The native-context bridge does not send a start time.
  • Calling instrument(webView) before L9Rum.initialize(...) emits a warning and is a no-op.
  • Detached or destroyed WebViews are pruned automatically.
  • In-WebView SPA routes are also tracked via Browser RUM startView() inside the WebView. Native-emitted WebView page views and Browser RUM route views are joined by session.id and native.view.id.
  • Calling L9Rum.startView() on a WebView host screen that is already auto-tracked is the wrong API — use setViewName() to rename the auto-tracked view in place. Before 1.5.0 that call also left a duplicate native view span.
  • From 1.6.0, an instrumented WebView host view is auto-named from the current main-frame URL: app.screen.name becomes the folded pathname (e.g. /health-record; numeric/UUID segments fold to ?), and view.url carries the full URL. An explicit startView / setViewName still wins.
  • From 1.6.2, each WebView page becomes its own view. Every committed main-frame navigation rotates the native view span into a fresh view.type=webview view, carrying view.url, the folded app.screen.name, its own native.view.id, and previous_url. The first committed URL names the existing host view; query-only changes and shared hosts (2+ WebViews) do not rotate. The name updates on full loads and in-WebView history changes.
    • Breaking (1.6.2): this replaces the earlier webview_page_load span event. Move any dashboards or alerts that queried webview_page_load to the view.type=webview view events.

Requires the Browser RUM JS SDK on the page. The JS SDK adopts the native session ID and fires l9rum:session_rollover when the session rotates, rotating the view span accordingly.

See the WebView Session Correlation guide for the full integration pattern, React Native/Flutter setup, the static-script path, auto-load Browser RUM, and verification steps.

Security

Client monitoring tokens are write-only and origin-scoped to your app’s package name. Safe to ship in the app binary.

Next steps

Once data is flowing, explore it in Discover > Applications — performance, errors, and sessions.

For the version history of this SDK, see the RUM changelog.


Troubleshooting

  • No data showing? Verify baseUrl, clientToken, and origin. Call L9Rum.sendTestEvent { ... } and read status and error (see Check the connection from code). Set debugLogs = true to see SDK logs in logcat.
  • error is HTTP 400: token origin not allowed? The origin in L9RumConfig does not match the allowed origin on your Client token. Set both to android://<package.name>, with your app’s exact package name. See Create a Client Monitoring Token.
  • error is session_not_sampled? The session is not sampled, so the SDK sends nothing. Set sampleRate = 100 while you verify the setup.
  • status is 0? The SDK got no HTTP response: a network error or a timeout. Check that the device can reach your baseUrl.
  • A 1.9.0+ API does not compile? The stable/v1 artifacts serve 1.8.0. Add a versioned dependency, for example io.last9:rum-android:1.14.0.

Please get in touch with us on Discord or Email if you have any questions.