boltZharp Docs
androidSDKs

Android

io.zharp:android sends an Android app's logs, crashes, ANRs and caught errors, and traces its screens and OkHttp requests into your API.

info
io.zharp:android 1.1.0

This SDK is new, and its API may still change before 1.0. Requires Android 5.0 (API 21) or later; core library desugaring below API 26.

It is built on the OpenTelemetry Java SDK and works from Kotlin and Java.

Install

// app/build.gradle.kts
dependencies {
    implementation("io.zharp:android:1.1.0")
}

It comes from Maven Central and declares the INTERNET permission itself.

Below Android 8 (minSdk under 26)

The OpenTelemetry Java SDK needs core library desugaring when the app's minSdk is below 26:

// app/build.gradle.kts — only when minSdk is below 26
android {
    compileOptions {
        isCoreLibraryDesugaringEnabled = true
    }
}

dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")
}

Without it, on Android 7.1 and older Zharp stays off — with one Logcat line — rather than crash the app.

Initialize

In Application.onCreate:

class ShopApp : Application() {
    override fun onCreate() {
        super.onCreate()
        Zharp.init(this) {
            key = "zpk_…"
            service = "shop-android"
            environment = "production"
            tracingOrigins = listOf("api.example.com") // your API: traces continue into it
        }
    }
}

Register the class with <application android:name=".ShopApp" …> in AndroidManifest.xml if you don't have one yet. The key is safe to ship in the app: it can only send. From Java:

ZharpOptions options = new ZharpOptions();
options.setKey("zpk_…");
options.setService("shop-android");
options.setEnvironment("production");
Zharp.init(this, options);

Logs

Zharp.log.info("Checkout opened", mapOf("items" to 3))   // debug, info, warn, error

Each log carries the session, user, device, screen and trace. By default only what you send with Zharp.log goes to Zharp. Set logs = true to also send what the app logs itself: Timber, System.out and System.err, java.util.logging and the app's own Logcat lines (android.util.Log), from INFO up. Swap android.util.Log for io.zharp.android.Log to give those lines their trace too.

Logs only

If you only want logs, turn tracing off. Logs, errors, and the user and session they belong to are still sent; no spans are recorded and no trace headers are added to outgoing requests.

Zharp.init(this) {
    key = "zpk_…"
    service = "shop-android"
    tracing = false
}

The logs show on the Logs page under the service name, and on the app's Logs tab with the user and session of each line. The key comes from an app — see Get a key. To add tracing later, remove the option; nothing else changes.

Errors

  • Uncaught exceptions, written to disk first and sent at once or on the next launch. The app still crashes as it would have.
  • ANRs: the main thread blocked for 5 seconds (anrThresholdMillis).
try {
    charge(order)
} catch (e: Exception) {
    Zharp.captureError(e, mapOf("orderId" to order.id))   // handled, with its stack
}

The library ships its own R8 rules; nothing to add to yours.

Readable stack traces

R8 and ProGuard rename your classes and methods. Add Zharp's Gradle plugin to the app module and crashes and errors from minified builds are shown — and grouped — by the original classes, methods, files and lines:

// app/build.gradle.kts
plugins {
    id("com.android.application")
    id("io.zharp.android-gradle") version "1.0.0"
}

zharp {
    appId = "123"   // the application's ID in Zharp
}

For each minified variant the plugin gives the build a new UUID, writes it into the app (the asset zharp-debug-meta.properties, which the SDK sends on every error), and after minify<Variant>WithR8 uploads that build's mapping.txt under it. No Node needed.

The upload needs a workspace API key with the artifacts:write scope — a secret, never in the repo (see The upload key). Without one, the upload is a dry run that prints what it would send, so local builds work as before.

# CI: an environment variable
ZHARP_AUTH_TOKEN=zh_…

# or your machine: ~/.gradle/gradle.properties — never the project's
zharp.authToken=zh_…
zharp { } optionAlso fromDefault
appIdZHARP_APP_ID, -Pzharp.appId—
authTokenZHARP_AUTH_TOKEN, -Pzharp.authTokennone: dry run
urlZHARP_URL, -Pzharp.urlhttps://api.zharp.io
uploadMappings—true; false still writes the UUID and prints it
failOnUploadError—true

To upload yourself instead (with uploadMappings = false), take the UUID from the build output:

npx @zharp/cli proguard upload app/build/outputs/mapping/release/mapping.txt --app 123 --uuid <uuid>

Tracing

A span per Activity and AndroidX Fragment shown. Add the interceptor to your OkHttp client (Retrofit uses it too): each request becomes a span, and requests to tracingOrigins hosts carry the trace headers.

val client = OkHttpClient.Builder()
    .addInterceptor(ZharpOkHttpInterceptor())
    .build()
Zharp.startSpan("load orders") { api.loadOrders() }      // a thrown exception marks it failed and is rethrown
Zharp.trackScreen("Checkout")                            // a Compose destination or custom navigation
Zharp.setTag("plan", "pro")

Zharp.openTelemetry hands out the underlying OpenTelemetry instance for other tracers and instrumentation libraries.

Request and response bodies

Off by default. Turn it on to see what a request sent and what came back, shown under the request in the trace: calls through an OkHttp client with ZharpOkHttpInterceptor: your tracingOrigins when you have set some (or urls), otherwise every call.

Zharp.init(this) {
    key = "zpk_…"
    // failed calls only; BodyCapture.all() for every one
    captureBodies = BodyCapture.errors()
}

// more control:
captureBodies = BodyCapture.all().apply {
    maxSize = 64 * 1024
    redactKeys = listOf("dateOfBirth")
    urls = listOf("api.shop.com")
}

// Java
options.setCaptureBodies(BodyCapture.errors());
  • Failed requests only (status 400 and above, or no response) by default; every request with the "all" mode.
  • Text (JSON, forms, XML, plain text) is kept up to 32 KB, up to 128 KB with the size option.
  • Every field name is kept. A file in an upload shows as [file photo.png · image/png · 240 KB], an inline image as [image/png · 24 KB], a body that isn't text as [binary · application/pdf · 1.2 MB] or [event stream]. File contents are never sent.
  • Your app reads and sends exactly what it did before.
  • One-shot and streaming request bodies are described, never written twice; responses are read with peekBody, so your code still gets all of it.
warning
Bodies can hold personal data

Values under keys that look secret — password, token, secret, apiKey, authorization, cookie, card, cvv, ssn and similar — are replaced with [Filtered] on the device, before anything is sent. The field stays; only its value is hidden, and under a secret object such as card each value inside is hidden and its keys kept. Anything else, such as names and email addresses, is sent as it is: add those keys to redactKeys.

Whether or not bodies are on, secret-looking values in URL query strings (?token=, key, sig, password …) are recorded as [Filtered].

User context

Zharp.setUser(id = user.id, email = user.email)   // once someone signs in
Zharp.clearUser()                                  // on sign-out: also starts a new session

Sessions end after 30 minutes in the background, or on clearUser(). Device and OS go on everything, with a random install-scoped device.id — not a hardware or advertising ID.

Options

OptionDefaultNotes
captureBodiesoffBodyCapture.errors() or BodyCapture.all(). See Request and response bodies.
key—Required. Without it nothing starts.
serviceThe package nameservice.name
environmentnone
releaseversionName (versionCode)
logsfalsetrue sends what the app logs: Timber, System.out/err, java.util.logging, Logcat
tracingtruefalse is logs only, whatever tracingOrigins says
tracingOriginsnoneHosts that get traceparent and baggage: api.example.com, api.example.com:8443, *.example.com, or a URL prefix
sampleRate1.0Share of traces kept; errors, crashes, ANRs and logs are always sent
captureCrashestrue
detectAnrstrueMain thread blocked for anrThresholdMillis (5,000)
trackScreenstrueA span per Activity and AndroidX Fragment shown
enabledtruefalse turns it off, e.g. in debug builds
debugfalseExplains in Logcat (tag Zharp) what was or wasn't sent

Telemetry goes as OTLP/protobuf, gzipped, every 5 seconds or 100 records, retried with backoff. Batches that still fail wait on disk (up to 200 files, 8 MB or 3 days) and go when the network is back. If the key is rejected, Logcat says so once and sending pauses for an hour. Nothing throws into the app.

Troubleshooting

Nothing arrives

On the app's setup page (Applications → the app → settings → Setup instructions), the verify step shows the first event as soon as it lands, and Send a test event checks the key on its own. If the test event arrives but your app's don't, the SDK isn't starting or isn't reaching Zharp:

  • Is init called, and before the code you expect to see? Without a key, the SDK starts nothing and says so once.
  • Does the service name match? With an app key everything goes to that app whatever it says; with a workspace key, service decides the app — see Keys.
  • Data is sent in batches every few seconds. A process that exits straight away should call flush first.
  • Logs and errors arrive but no traces? Check that tracing isn't turned off — see Logs only.
  • On Android 7.1 or older, is desugaring on? Without it, Zharp stays off — look for the Zharp line in Logcat.
  • Set debug = true to see in Logcat what the SDK does.

401 or 403

Ingest answers 401 when the key is missing, mistyped, revoked or rolled, and 403 when the request comes from an origin or IP address the key doesn't allow. Neither is retried: the SDK warns once and drops what was refused, and it never throws into your code. Copy the key again from the app's settings.