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
)

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) to exclude from network monitoring.
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.
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.

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()
)
FieldDescription
userIdUnique identifier of the user.
usernameDisplay name of the user.
emailUser’s email address.
metadataCustom user attributes for analytics segmentation.

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

By default, sessionSampleRate is an all-or-nothing gate: when a session is sampled out the entire SDK shuts down and nothing is sent. 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 always reach the backend regardless of sampling. Screenshot capture is governed by the session replay pipeline independently.

Back-compat note: An empty excludeFromSampling list (the default) preserves the existing behavior — when sessionSampleRate causes a session to be sampled out, the SDK does not initialize at all.

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

Instrumentation

Used to control which instrumentation modules are active.

InstrumentationConstantDescription
ErrorInstrumentation.ErrorCaptures handled and unhandled exceptions.
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. Sensitive headers (e.g., Authorization, Cookie) are never included unless explicitly added to the allowlist. Avoid adding security-sensitive headers to your capture rules in production.

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

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 may randomly drop sessions based on your sessionSampleRate configuration.

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