Skip to main content

Initialization and options

Initialization​

The initialize method bootstraps the Coralogix RUM SDK and should be called once — typically in your Application.onCreate() method.

ParameterTypeDescription
applicationApplicationYour app’s Application instance. Used for context and lifecycle management.
optionsCoralogixOptionsConfiguration object defining SDK behavior, network endpoints, and instrumentation preferences.
frameworkFrameworkIndicates the current runtime, to control hybrid bridge behavior (internal use only, setting this parameter would cause undefined behavior, use default value only - Framework.Android).
Note

Calling initialize() multiple times will be ignored after the first successful initialization.

Example:

class MyApp : Application() {
override fun onCreate() {
super.onCreate()

val options = CoralogixOptions(
applicationName = "MyApp",
coralogixDomain = CoralogixDomain.EU1,
publicKey = "<YOUR_PUBLIC_KEY>",
environment = "production",
version = BuildConfig.VERSION_NAME,
sessionSampleRate = 100,
labels = mapOf("platform" to "android", "someKey" to 3.14),
instrumentations = mapOf(
Instrumentation.Error to false,
Instrumentation.Network to false
)
)

CoralogixRum.initialize(this, options)
}
}

Check initialization:

if (CoralogixRum.isInitialized()) {
Log.d("TAG", "Coralogix SDK is initialized.")
}

CoralogixOptions​

The CoralogixOptions class defines all configuration settings for the SDK.

data class CoralogixOptions(
val applicationName: String,
val coralogixDomain: CoralogixDomain,
val publicKey: String,
val labels: Map<String, Any?> = mapOf(),
val environment: String = "",
val version: String = "",
val userContext: UserContext = UserContext(),
val viewContext: ViewContext = ViewContext(),
val instrumentations: Map<Instrumentation, Boolean> = mapOf(),
val mobileVitalsOptions: Map<MobileVitalType, Boolean> = mapOf(),
val ignoreUrls: List<String> = listOf(),
val ignoreErrors: List<String> = listOf(),
val collectIPData: Boolean = true,
val sessionSampleRate: Int = 100,
val excludeFromSampling: List<ExcludableInstrumentation> = emptyList(),
val traceParentInHeader: TraceParentInHeaderConfig = TraceParentInHeaderConfig(),
val debug: Boolean = false,
val proxyUrl: String? = null,
val beforeSend: ((EditableCxRum) -> EditableCxRum?)? = null,
val beforeSendCallback: ((List<Map<String, Any?>>) -> Unit)? = null,
val userInteractionOptions: UserInteractionOptions = UserInteractionOptions(),
val networkCaptureConfig: List<NetworkCaptureRule> = emptyList(),
val tracesExporter: ((CoralogixTraceExporterData) -> Unit)? = null,
val urlMasking: UrlMaskingOptions = UrlMaskingOptions()
)

Key fields​

FieldTypeDescription
applicationNameStringThe display name of your app, used in dashboards.
coralogixDomainCoralogixDomainTarget Coralogix ingestion domain (see below).
publicKeyStringThe public key used for authentication with Coralogix.
labelsMap<String, Any?>Global labels added to every event.
environmentStringEnvironment name (dev, staging, prod, etc.).
versionStringApplication version.
userContextUserContextDefault user context for the session.
viewContextViewContextDefault view context for the session.
instrumentationsMap<Instrumentation, Boolean>Can be used to disable SDK features (logs, errors, ANR, etc.).
mobileVitalsOptionsMap<MobileVitalType, Boolean>Can be used to disable mobile vitals detectors (fps, cpu, etc.).
ignoreUrlsList<String>URL substrings (or regex) the SDK leaves alone entirely — no network event and no traceparent header.
ignoreErrorsList<String>Exception messages (or regex) to exclude from reporting.
collectIPDataBooleanWhether to enrich outgoing events with user IP metadata.
sessionSampleRateIntSampling rate (0–100%) to control data volume.
excludeFromSamplingList<ExcludableInstrumentation>Instrumentation categories always exported regardless of sessionSampleRate. See Decoupling session sampling.
traceParentInHeaderTraceParentInHeaderConfigControls W3C traceparent header injection in network requests. Requires the network instrumentation to stay enabled.
debugBooleanEnables verbose SDK logs.
proxyUrlString?Optional proxy endpoint for data routing (see below).
beforeSend(EditableCxRum) -> EditableCxRum?Intercepts and modifies each event before sending (optional).
beforeSendCallback(List<Map<String, Any?>>) -> UnitCallback for hybrid frameworks, does nothing on native.
userInteractionOptionsUserInteractionOptionsConfiguration for user-interaction instrumentation (optional).
networkCaptureConfigList<NetworkCaptureRule>Rules to capture request/response headers and payloads (optional).
tracesExporter(CoralogixTraceExporterData) -> UnitOptional callback that receives raw OTLP span data, enabling distributed-tracing integration. It runs before beforeSend, so your beforeSend redaction does not apply to it. See Receiving raw OTLP span data.
urlMaskingUrlMaskingOptionsAdds to the URL parameters the SDK masks, or changes how it masks them. Masking is always on. See URL masking.

CoralogixDomain​

Defines the target Coralogix ingestion endpoint. The regional domains available to customer applications are:

DomainConstantURL
EU1CoralogixDomain.EU1https://ingress.eu1.rum-ingress-coralogix.com
EU2CoralogixDomain.EU2https://ingress.eu2.rum-ingress-coralogix.com
US1CoralogixDomain.US1https://ingress.us1.rum-ingress-coralogix.com
US2CoralogixDomain.US2https://ingress.us2.rum-ingress-coralogix.com
US3CoralogixDomain.US3https://ingress.us3.rum-ingress-coralogix.com
AP1CoralogixDomain.AP1https://ingress.ap1.rum-ingress-coralogix.com
AP2CoralogixDomain.AP2https://ingress.ap2.rum-ingress-coralogix.com
AP3CoralogixDomain.AP3https://ingress.ap3.rum-ingress-coralogix.com
Tip

Choose the domain corresponding to your Coralogix account region to minimize latency.

UserContext​

Defines information about the current user.

data class UserContext(
val userId: String = "",
val username: String = "",
val email: String = "",
val metadata: Map<String, String> = mapOf(),
val accountId: String? = null,
val accountName: String? = null
)
FieldDescription
userIdUnique identifier of the user.
usernameDisplay name of the user.
emailUser’s email address.
metadataCustom user attributes for analytics segmentation.
accountIdOptional. Identifier of the account the user belongs to.
accountNameOptional. Display name of the account the user belongs to.

ViewContext​

Describes the currently visible app screen.

data class ViewContext(
val viewName: String = "",
val activityName: String = "",
val fragmentName: String = ""
)
FieldDescription
viewNameLogical name of the current screen.
activityNameHost activity class name.
fragmentNameActive fragment class name.

Decoupling session sampling​

sessionSampleRate decides what is reported, not whether the SDK runs. The SDK always initializes, so a sampled-out session still adds the traceparent header to outgoing requests and your traces stay correlated; it simply sends nothing else. Use excludeFromSampling to keep specific instrumentation categories flowing at 100 % even when the session is sampled out.

This is useful when you want a low session sample rate (e.g. 10 %) to reduce RUM data volume, but still need every custom log message to reach Coralogix for debugging.

val options = CoralogixOptions(
applicationName = "MyApp",
coralogixDomain = CoralogixDomain.EU1,
publicKey = "<YOUR_PUBLIC_KEY>",
sessionSampleRate = 10, // sample 10 % of sessions
excludeFromSampling = listOf(
ExcludableInstrumentation.Logs, // always export custom logs
ExcludableInstrumentation.Errors // always export errors
)
)

ExcludableInstrumentation values​

ValueExported event typeSource API
ErrorserrorAutomatic crash/exception capture
LogslogCoralogixRum.log(...)
Networknetwork-requestAutomatic network instrumentation
UserInteractionsuser-interactionAutomatic tap/scroll capture
MobileVitalsmobile-vitalsCPU, memory, FPS metrics
CustomSpancustom-spanCoralogixRum.getCustomTracer()
CustomMeasurementcustom-measurementCoralogixRum.sendCustomMeasurement(...)
NavigationnavigationAutomatic navigation event capture
Lifecyclelife-cycleApp foreground/background transitions
Note

Screenshot (session-replay frames) and internal SDK init events are intentionally absent from this list. Internal events from a sampled-out session are sent only when excludeFromSampling lists at least one category; with an empty list, a sampled-out session sends nothing at all, matching the browser SDK. Session-replay frames are governed by the session replay pipeline, which does not record a sampled-out session at all.

The instrumentations map has the final say. excludeFromSampling only relaxes the sampling condition, so it can never switch something back on that you set to false in instrumentations — a category disabled there stays disabled on sampled-in and sampled-out sessions alike. On a sampled-in session the exclude list has no effect at all.

Categories that are neither sampled in nor excluded are not started, so a sampled-out session does no work collecting events it would discard. When such a session later rotates into being sampled in — after 15 minutes of inactivity, after an hour, or when you call createNewSession() — the categories it skipped start then, and reporting resumes in full.

Inside a beforeSend hook, EditableCxRum.isSessionSampledIn tells you whether an event came from a sampled-in session or reached you only via excludeFromSampling, so you can filter excluded categories further (for example, keep only ANRs).

The traceparent sampled flag​

The last byte of the traceparent header is the W3C sampled flag. From 2.24.2 it carries the session's sampling decision for that request: 00 when the session is sampled out and excludeFromSampling does not include Network, so the request only propagates trace context, and 01 otherwise. Before 2.24.2 every request carried 01.

The flag reflects sampling alone, so 01 is not a guarantee that the event arrives. These still drop a reported event after the header has gone out, and all of them leave the flag at 01:

  • an event your beforeSend callback returns null for
  • a request your app sends while the session is idle, which it becomes after 15 minutes without a touch or an activity resuming
Note

In a React Native app with the Coralogix Gradle plugin applied, this SDK injects the header, so the flag behaves as described here. Without the plugin, React Native injects the header from JavaScript, and Flutter always injects it from Dart; in both cases it currently always carries 01.

If your code builds the traceparent header itself instead of letting this SDK inject it, call CoralogixRum.networkRequestSampling() when each request starts and use its isSampled for the flag: 01 for true, 00 for false. Do not cache the answer, because the session can change at any time. isSampled is also false while network instrumentation is switched off and before the SDK is initialized. A request sent then carries 00 and is not reported, so the header and the events still agree. When you report the request with CoralogixRum.reportNetworkRequest, pass isSampled in NetworkRequestDetails.traceparentSampled and sessionId in NetworkRequestDetails.traceparentSessionId. The reported event then matches the flag the request was sent with and belongs to the session the request started in, even if the session changed while it was in flight. These are available from version 2.25.0.

import com.coralogix.android.sdk.CoralogixRum
import com.coralogix.android.sdk.internal.features.instrumentations.network.NetworkRequestDetails

val sampling = CoralogixRum.networkRequestSampling()
val traceparent = "00-$traceId-$spanId-${if (sampling.isSampled) "01" else "00"}"
// Send the request with this traceparent header, then report it:
CoralogixRum.reportNetworkRequest(
NetworkRequestDetails(
traceId = traceId,
spanId = spanId,
method = "GET",
url = url,
statusCode = 200,
traceparentSampled = sampling.isSampled,
traceparentSessionId = sampling.sessionId,
)
)

Instrumentation​

Used to control which instrumentation modules are active.

InstrumentationConstantDescription
ErrorInstrumentation.ErrorCaptures handled and unhandled exceptions and native crashes.
NetworkInstrumentation.NetworkReports network requests and responses.
CustomInstrumentation.CustomAllows sending custom events or metrics.
MobileVitalsInstrumentation.MobileVitalsTracks CPU, memory, and FPS.
AnrInstrumentation.AnrDetects Application Not Responding (ANR) events.
LifecycleInstrumentation.LifecycleObserves app foreground/background transitions.
UserInteractionInstrumentation.UserInteractionTracks taps, scrolls, and other interactions.
Note

Instrumentations are enabled by default.

Mobile vital options​

Used to control which mobile vitals detectors are active.

InstrumentationConstantDescription
ColdStartTimeMobileVitalType.ColdStartTimeMeasures the app's launch time
WarmStartTimeMobileVitalType.WarmStartTimeMeasures how long it takes for the app to return from the background.
CpuUsageMobileVitalType.CpuUsageMeasures cpu usage.
MemoryUsageMobileVitalType.MemoryUsageMeasures memory usage.
SlowFrozenFramesMobileVitalType.SlowFrozenFramesDetects frames that were slow to render or frozen.
FpsMobileVitalType.FpsMeasures the application screen refresh rate per second.
Note

Mobile vitals detectors are enabled by default.

Network capture configuration​

The networkCaptureConfig option lets you capture request/response headers and payloads for matching network requests. Rules are matched in order — the first match wins.

data class NetworkCaptureRule(
val url: String? = null, // Exact URL match
val urlPattern: Regex? = null, // Regex pattern match
val reqHeaders: List<String>? = null, // Request headers to capture (allowlist)
val resHeaders: List<String>? = null, // Response headers to capture (allowlist)
val collectReqPayload: Boolean = false, // Capture request body
val collectResPayload: Boolean = false // Capture response body
)
FieldDescription
urlExact URL string to match.
urlPatternRegex pattern to match against the full request URL.
reqHeadersAllowlist of request header names to capture. Matching is case-insensitive.
resHeadersAllowlist of response header names to capture. Matching is case-insensitive.
collectReqPayloadWhen true, captures the request body if it is text-based and ≤ 1024 characters.
collectResPayloadWhen true, captures the response body if it is text-based and ≤ 1024 characters.

Example​

val options = CoralogixOptions(
// ... other options ...
networkCaptureConfig = listOf(
NetworkCaptureRule(
urlPattern = Regex(".*api\\.example\\.com.*"),
reqHeaders = listOf("Accept", "Content-Type"),
resHeaders = listOf("Content-Type", "X-Request-Id"),
collectReqPayload = true,
collectResPayload = true
)
)
)

URL matching​

Each rule requires either url (exact match) or urlPattern (regex). Rules are evaluated in list order and the first matching rule is applied — subsequent rules are ignored.

Header capture​

Header names in reqHeaders/resHeaders are matched case-insensitively against the actual headers sent/received. The captured header keys use the casing from your allowlist, not the casing from the network layer.

Payload capture​

Payloads are only captured when:

  • collectReqPayload / collectResPayload is true in the matching rule.
  • The Content-Type is text-based: application/json, text/*, application/javascript, or application/xml.
  • The payload is ≤ 1024 characters. If it exceeds this limit, the payload is dropped entirely (not truncated).

Security considerations​

Only headers explicitly listed in reqHeaders/resHeaders are captured; nothing is captured by default and there is no wildcard.

Warning

A header you list is captured exactly as it is sent, with no masking, and that includes credential headers such as Authorization and Cookie. Do not list a header that carries a credential.

EditableCxRum​

A mutable representation of an event intercepted via beforeSend.

data class EditableCxRum(
val eventContext: EventContext? = null,
val labels: Map<String, Any?>? = null,
val spanId: String? = null,
val traceId: String? = null,
val environment: String? = null,
val viewContext: ViewContext? = null,
val isSnapshotEvent: Boolean? = null,
val errorContext: EditableErrorContext? = null,
val logContext: LogContext? = null,
val networkRequestContext: NetworkRequestContext? = null,
val userContext: UserContext? = null,
val lifecycleContext: LifecycleContext? = null,
val customMeasurementContext: CustomMeasurementContext? = null,
val interactionContext: InteractionContext? = null,
val isSessionSampledIn: Boolean? = null
)

This class is used in beforeSend hooks to inspect or modify event data before it’s sent to Coralogix.

interactionContext carries isMaskedElement (is_masked_element on the wire, always present) — whether the interaction targeted content that session replay masked. See Privacy and masking for ready-made beforeSend recipes built on it.

isSessionSampledIn is read-only: it reports whether the event's session was sampled in by sessionSampleRate. false means the event is being sent only because its category is listed in excludeFromSampling, or because it is an internal SDK event, which a sampled-out session sends whenever excludeFromSampling is non-empty. Changing it in beforeSend has no effect. Use it to filter excluded categories further — for example, with a low sample rate and ExcludableInstrumentation.Errors excluded, keep only ANRs from sampled-out sessions:

beforeSend = { event ->
val isError = event.errorContext != null
when {
!isError -> event // non-error events pass through
event.isSessionSampledIn == true -> event // sampled-in sessions keep all errors
event.errorContext?.type == "ANR" -> event // sampled-out: keep only ANRs
else -> null // drop the rest
}
}

URL masking​

Starting with version 2.27.0, the SDK masks secrets in every URL it reports before the URL is stored on an event: network request URLs, including those reported through reportNetworkRequest, the URLs inside an error's message or a failed request's error message, the script URLs in JavaScript stack frames, and view names, both the initial viewContext and those set through setViewContext. A masked value reads [REDACTED]; the parameter name and the rest of the URL are kept as sent.

By default the SDK masks:

  • The value of a query or fragment parameter whose name contains token, secret, password, passwd, passphrase, apikey, signature, credential, jwt, session, sessid, oauth, saml, privatekey, accesskey or nonce.
  • The value of a parameter named exactly code, state, codeverifier, assertion, clientassertion, devicecode, usercode, bearer, auth, authorization, authcode, authkey, sig, hmac, key, pass, pwd, otp, oobcode, sid or ticket.
  • JWTs anywhere in the URL, the path included.
  • Credentials in the URL: https://user:password@host is reported as https://[REDACTED]@host.
  • Session ids in the path, such as ;jsessionid=.
  • The same parameters percent-encoded inside another parameter's value, such as a return URL.

Names are compared in lowercase with every non-alphanumeric character removed, so api_key, apiKey and API-Key are the same name. For example, https://example.com/callback?code=abc&page=2#access_token=xyz is reported as https://example.com/callback?code=[REDACTED]&page=2#access_token=[REDACTED].

Masking cannot be turned off, and a built-in name cannot be removed. Use urlMasking to add to it:

import com.coralogix.android.sdk.model.UrlMaskingMode
import com.coralogix.android.sdk.model.UrlMaskingOptions

val options = CoralogixOptions(
// ... other options ...
urlMasking = UrlMaskingOptions(
additionalParams = listOf("tenant_id"),
additionalParamPatterns = listOf(Regex("^customer")),
mode = UrlMaskingMode.MASK
)
)
FieldTypeDescription
additionalParamsList<String>More parameter names to mask. Each matches a whole name, compared the same way as the built-in names.
additionalParamPatternsList<Regex>Patterns tested against each decoded parameter name. A name any pattern finds is masked.
modeUrlMaskingModeMASK (default) masks sensitive values only. MASK_ALL masks every parameter value and keeps the names. DROP_QUERY removes the query and the fragment.

In every mode, JWTs in the path, credentials in the URL and path session ids are masked too.

ignoreUrls and the URL matching in networkCaptureConfig use the original URL, so your existing patterns keep matching. beforeSend, beforeSendCallback and tracesExporter only see the masked URL.

ProxyUrl​

Used to configure a proxy endpoint for data routing. It is your responsibility to forward the data to the Coralogix ingestion endpoint. The ingestion endpoint would be available under the cxforward query parameter, for example: https://your.proxy.com/?cxforward=ingestion.url.com

Session sampling​

The SDK reports a random subset of sessions, based on your sessionSampleRate configuration. Sessions outside that subset still initialize the SDK and still propagate trace context — they just do not send events. See Decoupling session sampling to keep specific categories flowing at 100 %.

// Example: Report 20% of all sessions
val options = CoralogixOptions(sessionSampleRate = 20)
Last updated on