# Initialization and options

Copy as Markdown[Open in ChatGPT](https://chatgpt.com/?q=Read%20https%3A%2F%2Fcoralogix.com%2Fdocs%2Fuser-guides%2Frum%2Fsdk-installation%2Fandroid%2Fconfiguration%2Finitialization.md%20and%20help%20me%20with%20my%20question%20about%20this%20Coralogix%20documentation%20page.)[Open in Claude](https://claude.ai/new?q=Read%20https%3A%2F%2Fcoralogix.com%2Fdocs%2Fuser-guides%2Frum%2Fsdk-installation%2Fandroid%2Fconfiguration%2Finitialization.md%20and%20help%20me%20with%20my%20question%20about%20this%20Coralogix%20documentation%20page.)

## Initialization[​](#initialization "Direct link to Initialization")

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

| Parameter       | Type               | Description                                                                                                                                                                                |
| --------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **application** | `Application`      | Your app’s `Application` instance. Used for context and lifecycle management.                                                                                                              |
| **options**     | `CoralogixOptions` | Configuration object defining SDK behavior, network endpoints, and instrumentation preferences.                                                                                            |
| **framework**   | `Framework`        | Indicates 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[​](#coralogixoptions "Direct link to 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[​](#key-fields "Direct link to Key Fields")

| Field                      | Type                                   | Description                                                                                                                                    |
| -------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| **applicationName**        | `String`                               | The display name of your app, used in dashboards.                                                                                              |
| **coralogixDomain**        | `CoralogixDomain`                      | Target Coralogix ingestion domain (see below).                                                                                                 |
| **publicKey**              | `String`                               | The public key used for authentication with Coralogix.                                                                                         |
| **labels**                 | `Map<String, Any?>`                    | Global labels added to every event.                                                                                                            |
| **environment**            | `String`                               | Environment name (`dev`, `staging`, `prod`, etc.).                                                                                             |
| **version**                | `String`                               | Application version.                                                                                                                           |
| **userContext**            | `UserContext`                          | Default user context for the session.                                                                                                          |
| **viewContext**            | `ViewContext`                          | Default view context for the session.                                                                                                          |
| **instrumentations**       | `Map<Instrumentation, Boolean>`        | Can be used to disable SDK features (logs, errors, ANR, etc.).                                                                                 |
| **mobileVitalsOptions**    | `Map<MobileVitalType, Boolean>`        | Can be used to disable mobile vitals detectors (fps, cpu, etc.).                                                                               |
| **ignoreUrls**             | `List<String>`                         | URL substrings (or regex) to exclude from network monitoring.                                                                                  |
| **ignoreErrors**           | `List<String>`                         | Exception messages (or regex) to exclude from reporting.                                                                                       |
| **collectIPData**          | `Boolean`                              | Whether to enrich outgoing events with user IP metadata.                                                                                       |
| **sessionSampleRate**      | `Int`                                  | Sampling rate (0–100%) to control data volume.                                                                                                 |
| **excludeFromSampling**    | `List<ExcludableInstrumentation>`      | Instrumentation categories always exported regardless of `sessionSampleRate`. See [Decoupling session sampling](#decoupling-session-sampling). |
| **traceParentInHeader**    | `TraceParentInHeaderConfig`            | Controls W3C traceparent header injection in network requests.                                                                                 |
| **debug**                  | `Boolean`                              | Enables verbose SDK logs.                                                                                                                      |
| **proxyUrl**               | `String?`                              | Optional proxy endpoint for data routing (see below).                                                                                          |
| **beforeSend**             | `(EditableCxRum) -> EditableCxRum?`    | Intercepts and modifies each event before sending (optional).                                                                                  |
| **beforeSendCallback**     | `(List<Map<String, Any?>>) -> Unit`    | Callback for hybrid frameworks, does nothing on native.                                                                                        |
| **userInteractionOptions** | `UserInteractionOptions`               | Configuration for user-interaction instrumentation (optional).                                                                                 |
| **networkCaptureConfig**   | `List<NetworkCaptureRule>`             | Rules to capture request/response headers and payloads (optional).                                                                             |
| **tracesExporter**         | `(CoralogixTraceExporterData) -> Unit` | Optional callback that receives raw OTLP span data, enabling distributed-tracing integration.                                                  |

### CoralogixDomain[​](#coralogixdomain "Direct link to CoralogixDomain")

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

| Domain  | Constant              | URL                                             |
| ------- | --------------------- | ----------------------------------------------- |
| **EU1** | `CoralogixDomain.EU1` | `https://ingress.eu1.rum-ingress-coralogix.com` |
| **EU2** | `CoralogixDomain.EU2` | `https://ingress.eu2.rum-ingress-coralogix.com` |
| **US1** | `CoralogixDomain.US1` | `https://ingress.us1.rum-ingress-coralogix.com` |
| **US2** | `CoralogixDomain.US2` | `https://ingress.us2.rum-ingress-coralogix.com` |
| **US3** | `CoralogixDomain.US3` | `https://ingress.us3.rum-ingress-coralogix.com` |
| **AP1** | `CoralogixDomain.AP1` | `https://ingress.ap1.rum-ingress-coralogix.com` |
| **AP2** | `CoralogixDomain.AP2` | `https://ingress.ap2.rum-ingress-coralogix.com` |
| **AP3** | `CoralogixDomain.AP3` | `https://ingress.ap3.rum-ingress-coralogix.com` |

Tip

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

### UserContext[​](#usercontext "Direct link to 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()

)
```

| Field        | Description                                        |
| ------------ | -------------------------------------------------- |
| **userId**   | Unique identifier of the user.                     |
| **username** | Display name of the user.                          |
| **email**    | User’s email address.                              |
| **metadata** | Custom user attributes for analytics segmentation. |

### ViewContext[​](#viewcontext "Direct link to ViewContext")

Describes the currently visible app screen.

```
data class ViewContext(

    val viewName: String = "",

    val activityName: String = "",

    val fragmentName: String = ""

)
```

| Field            | Description                         |
| ---------------- | ----------------------------------- |
| **viewName**     | Logical name of the current screen. |
| **activityName** | Host activity class name.           |
| **fragmentName** | Active fragment class name.         |

### Decoupling session sampling[​](#decoupling-session-sampling "Direct link to 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[​](#excludableinstrumentation-values "Direct link to excludableinstrumentation-values")

| Value               | Exported event type  | Source API                                |
| ------------------- | -------------------- | ----------------------------------------- |
| `Errors`            | `error`              | Automatic crash/exception capture         |
| `Logs`              | `log`                | `CoralogixRum.log(...)`                   |
| `Network`           | `network-request`    | Automatic network instrumentation         |
| `UserInteractions`  | `user-interaction`   | Automatic tap/scroll capture              |
| `MobileVitals`      | `mobile-vitals`      | CPU, memory, FPS metrics                  |
| `CustomSpan`        | `custom-span`        | `CoralogixRum.getCustomTracer()`          |
| `CustomMeasurement` | `custom-measurement` | `CoralogixRum.sendCustomMeasurement(...)` |
| `Navigation`        | `navigation`         | Automatic navigation event capture        |
| `Lifecycle`         | `life-cycle`         | App 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`](#editablecxrum) 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[​](#instrumentation "Direct link to Instrumentation")

Used to control which instrumentation modules are active.

| Instrumentation     | Constant                          | Description                                      |
| ------------------- | --------------------------------- | ------------------------------------------------ |
| **Error**           | `Instrumentation.Error`           | Captures handled and unhandled exceptions.       |
| **Network**         | `Instrumentation.Network`         | Reports network requests and responses.          |
| **Custom**          | `Instrumentation.Custom`          | Allows sending custom events or metrics.         |
| **MobileVitals**    | `Instrumentation.MobileVitals`    | Tracks CPU, memory, and FPS.                     |
| **Anr**             | `Instrumentation.Anr`             | Detects Application Not Responding (ANR) events. |
| **Lifecycle**       | `Instrumentation.Lifecycle`       | Observes app foreground/background transitions.  |
| **UserInteraction** | `Instrumentation.UserInteraction` | Tracks taps, scrolls, and other interactions.    |

Note

Instrumentations are enabled by default.

### Mobile Vital Options[​](#mobile-vital-options "Direct link to Mobile Vital Options")

Used to control which mobile vitals detectors are active.

| Instrumentation      | Constant                           | Description                                                           |
| -------------------- | ---------------------------------- | --------------------------------------------------------------------- |
| **ColdStartTime**    | `MobileVitalType.ColdStartTime`    | Measures the app's launch time                                        |
| **WarmStartTime**    | `MobileVitalType.WarmStartTime`    | Measures how long it takes for the app to return from the background. |
| **CpuUsage**         | `MobileVitalType.CpuUsage`         | Measures cpu usage.                                                   |
| **MemoryUsage**      | `MobileVitalType.MemoryUsage`      | Measures memory usage.                                                |
| **SlowFrozenFrames** | `MobileVitalType.SlowFrozenFrames` | Detects frames that were slow to render or frozen.                    |
| **Fps**              | `MobileVitalType.Fps`              | Measures the application screen refresh rate per second.              |

Note

Mobile vitals detectors are enabled by default.

### Network Capture Configuration[​](#network-capture-configuration "Direct link to 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

)
```

| Field                 | Description                                                                        |
| --------------------- | ---------------------------------------------------------------------------------- |
| **url**               | Exact URL string to match.                                                         |
| **urlPattern**        | Regex pattern to match against the full request URL.                               |
| **reqHeaders**        | Allowlist of request header names to capture. Matching is case-insensitive.        |
| **resHeaders**        | Allowlist of response header names to capture. Matching is case-insensitive.       |
| **collectReqPayload** | When `true`, captures the request body if it is text-based and ≤ 1024 characters.  |
| **collectResPayload** | When `true`, captures the response body if it is text-based and ≤ 1024 characters. |

#### Example[​](#example "Direct link to 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[​](#url-matching "Direct link to 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-capture "Direct link to 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[​](#payload-capture "Direct link to 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[​](#security-considerations "Direct link to 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[​](#editablecxrum "Direct link to 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](#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[​](#proxyurl "Direct link to 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[​](#session-sampling "Direct link to Session Sampling")

The SDK may randomly drop sessions based on your `sessionSampleRate` configuration.

```
// Example: Capture 20% of all sessions

val options = CoralogixOptions(sessionSampleRate = 20)
```
