Early accessBy invitation, and the SDKs aren't published yet.Ask for an invitation
Skip to Content
Docs

Android

Structured logs from your Android app, in Kotlin or Java. No dependencies beyond the Kotlin standard library.

Phones and tablets, in Kotlin or Java

The Android SDK needs Android 7.0 (API 24) or later. It is written in Kotlin, has no dependencies beyond the Kotlin standard library (no OkHttp, coroutines or AndroidX), and every function can be called from Java too.

Internal preview: this package isn't published yet. Until it is, Gradle can't fetch com.lyrelog:lyrelog-android: it isn't on Maven Central, and the repository is private and has no release yet.

Install

From Maven Central, in your app module's build.gradle.kts:

dependencies {
    implementation("com.lyrelog:lyrelog-android:0.1.0")
}

The library adds the INTERNET permission to your app's manifest.

Start

Start once, as early as possible, in your Application's onCreate. A second call while it runs is ignored. Events logged before start are ignored too, but setUser and setConsent called before start are kept and applied when it runs.

import android.app.Application
import com.lyrelog.Configuration
import com.lyrelog.Lyrelog

class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        Lyrelog.start(this, Configuration(
            apiKey = "lyr_ing_...",          // ingest-only: it can append events, never read them
        ))
    }
}

Name the class in the manifest (<application android:name=".MyApp" ...>) if your app doesn't have an Application yet.

Events go to https://ingest.lyrelog.com. Pass endpoint only to send them somewhere else. It is the base URL (a pasted .../v1/events:batch path is stripped) and must be https; plain http works only for localhost, 127.0.0.1 or ::1, and on the emulator for 10.0.2.2 (see In development and tests). With any other endpoint nothing is sent and the events stay on the device.

Log events

One function per level: trace, debug, info, notice, warning, error, critical, or log(level, message, ...) with a Level.

Lyrelog.info("checkout_done", attrs = mapOf("items" to 3, "latency_ms" to ms))
Lyrelog.error("payment_declined", category = "checkout",
              attrs = mapOf("code" to 51), payload = mapOf("response" to raw))

Attributes are a Map<String, Any?>: strings, numbers, booleans, null, lists (their items sent as strings) and nested maps up to 4 levels. The payload is any map, list or value, for the detail you only read when you open one event.

Loggers for each area

A logger stamps its category on every event, like an Android log tag. It has every level, plus log and captureError. It is cheap to make and keep, and logs into whatever SDK is running when it is called.

val sync = Lyrelog.logger("sync")
sync.warning("sync_conflict", mapOf("records" to 2))

Users

Lyrelog.setUser(playerId)   // attached to every following event
Lyrelog.setUser(null)       // on sign-out

Lyrelog.sessionId gives the current session id, for example to show in a support screen.

The user id isn't saved between launches: call setUser again on each launch, once you know who the person is.

Screens

Say where the person is. Lyrelog logs screen_viewed (area navigation) with the screen before and the seconds spent on it, and tags every following event with a screen attribute.

override fun onResume() {
    super.onResume()
    Lyrelog.screen("Settings")
}

In Compose, call it from a LaunchedEffect when a destination is shown. The event carries screen, previous_screen and seconds_on_previous. Calling screen again with the same name logs nothing. screen takes extra attrs for the screen_viewed event. Turn the tagging off with attachScreen = false.

automaticScreens = true does it for every Activity that comes to the front, named by its class (SettingsActivity). It is off by default: Compose and fragment apps have many screens in one Activity, and a name you choose reads better on the dashboard.

Errors you catch

try {
    store.purchase(product)
} catch (e: IOException) {
    Lyrelog.captureError(e, category = "store")
}

It sends the exception event every SDK sends: level error, the attributes error_type (the class name) and error_message, and a payload with the description, up to 60 frames, the causes (up to 8, 20 frames each) and suppressed exceptions. attrs adds your own; level changes the level. Each logger has captureError too.

Frames are as the VM reports them. When the app is minified with R8, run retrace with the build's mapping file to get the original names.

Crashes

An uncaught exception is written to disk on the spot, on the thread that is dying, together with any event still on its way to the disk. Then it is handed to the handler that was there before (the system's crash dialog, or another crash reporter that installed one first). Nothing is sent then: the process is about to end.

The next launch sends it, at the time it happened and in the session it ended, in the diagnostics area, like the Swift SDK's crash reports, so both platforms' crashes sit together in the dashboard:

EventLevelWhat it carries
app_crashedcriticalerror_type, error_message, handled: false, mechanism: uncaught_exception, and a payload with the thread, the frames, the causes and suppressed exceptions

It's on by default; turn it off with captureCrashes = false. Native crashes and ANRs aren't reported.

Environments and platform

When it starts, the SDK picks the environment: development when the app is debuggable (android:debuggable, every debug build), production otherwise.

Your own debug builds send development, while the dashboard opens on production: pick development in the top bar to see them.

The platform is android. Override either in the configuration:

Configuration(
    apiKey = key,
    environment = if (BuildConfig.FLAVOR == "beta") "beta" else null,   // null = detected
    platform = null,
)

Any name works: lowercase letters, digits, - and _, up to 32. Other text is turned into a valid name (Staging EU becomes staging-eu).

Lyrelog.start(this, Configuration(apiKey = key, consent = Consent.PENDING))
// later, when the person chooses:
Lyrelog.setConsent(Consent.GRANTED)   // sends, including what was kept while pending
Lyrelog.setConsent(Consent.DENIED)    // deletes everything and stops recording

PENDING keeps events on the device without sending them. Nothing is uploaded unless consent is granted, including what an earlier launch left. Starting with Consent.DENIED deletes anything still queued from an earlier launch and the install id, and records nothing. A setConsent before start wins over Configuration.consent.

Consent isn't saved between launches: store the person's choice yourself and pass it to start each time.

A complete app

Start with the stored consent, set the person when they sign in and tag screens:

import android.app.Application
import com.lyrelog.Configuration
import com.lyrelog.Consent
import com.lyrelog.Lyrelog

class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        val prefs = getSharedPreferences("settings", MODE_PRIVATE)
        val consent = when (prefs.getString("diagnostics", null)) {
            "granted" -> Consent.GRANTED
            "denied" -> Consent.DENIED
            else -> Consent.PENDING
        }
        Lyrelog.start(this, Configuration(apiKey = "lyr_ing_...", consent = consent))
    }
}

class HomeActivity : AppCompatActivity() {
    override fun onResume() {
        super.onResume()
        Lyrelog.screen("Home")
    }

    private fun signedIn(account: Account) {
        Lyrelog.setUser(account.id)
        Lyrelog.info("signed_in", category = "auth")
    }
}

fun choose(context: Context, allowed: Boolean) {
    context.getSharedPreferences("settings", Context.MODE_PRIVATE).edit()
        .putString("diagnostics", if (allowed) "granted" else "denied").apply()
    Lyrelog.setConsent(if (allowed) Consent.GRANTED else Consent.DENIED)
}

Flush and stop

Going to the background already sends (when the last Activity stops; a rotation doesn't count), so you rarely need to.

Lyrelog.flushInBackground()   // send now, without waiting
Lyrelog.flush()               // write everything to disk and send, waiting up to 5 seconds
Lyrelog.stop()                // send what's queued (up to 2 seconds), then stop
Lyrelog.stopNow()             // stop at once; what was logged goes with the next launch

flush and stop block, so never call them on the main thread. flush returns true when it finished in time, and respects a Retry-After the server asked for: it doesn't send sooner. After stop, start can be called again.

In development and tests

Don't call Lyrelog.start in unit tests: anything logged before start is ignored, so the rest of your code runs unchanged. mirrorToLogcat = true also prints every event to logcat (tag Lyrelog) while you work.

Debug builds send environment development. To send from the emulator to an endpoint running on your computer, use http://10.0.2.2 and its port as the endpoint (10.0.2.2 is your computer, as the emulator sees it), in the debug build only:

  • Allow plain http to 10.0.2.2. Android blocks it unless the app allows it: add a network security config to the debug build that permits cleartext for that one address.
  • On Android 17, an app targeting API 37 also needs ACCESS_LOCAL_NETWORK to reach a private address like 10.0.2.2; without it the connection just times out. Declare the permission in the debug manifest (src/debug/AndroidManifest.xml) and grant it: adb shell pm grant <your.app> android.permission.ACCESS_LOCAL_NETWORK.

This is only for local development. The hosted ingest is a public https address and needs neither.

Verified events

A verified event is one that can't have been sent by someone who copied the public ingest key out of an app or a web page. What that proves, and what it doesn't, is on Verified events.

An Android app's events are verified with Key Attestation: the phone's secure hardware proves that they come from your own app, signed with your certificate, on a real device that hasn't been rooted or unlocked. Lyrelog checks it on its own servers; no Google account, Play Integrity or Google Cloud project is involved.

It is on by default (attest in Configuration); set it up in the project:

  1. In Project settings, under Verified events from your Android apps, add your package and the SHA-256 fingerprint of each certificate that signs builds that send events: Play's app signing key (Play Console, Test and release, App integrity) and, for builds you sign yourself, the one ./gradlew signingReport shows.
  2. That's all in the app. To turn it off:
Lyrelog.start(this, Configuration(apiKey = "lyr_ing_...", attest = false))

Once per install the SDK makes a key in the phone's secure hardware (StrongBox or the trusted execution environment) and has the device attest it; from then on its batches carry a token and arrive verified (verified_by is key_attestation). The token lasts 24 hours and is renewed in the background before it ends. Sending never waits for this: until the app has a token, and whenever anything fails, events are sent unverified.

  • Emulators never verify, and the SDK doesn't try there.
  • Until the project has an Android app set up, or when the key is refused or the device can't attest, the SDK turns attestation off for that launch and says so once in logcat.
  • A device the server refuses (a rooted phone, an unlocked bootloader, a certificate the project doesn't list) tries again a day later.
  • Denying consent deletes the attested key and its record (noBackupFilesDir/lyrelog/attest.json).

Until it's set up, events arrive unverified and count toward the daily share of one address. Before making the project accept only verified events from android, check in the explorer that your real users' events arrive verified: events from older versions, emulators and refused devices would be held back with a 425.

Events your own servers send with a server key, lyr_srv_..., are verified. Never put a server key in an app: anything shipped in an APK can be read.

To check, open the explorer: an opened event says it under Context, in its Sender line: Verified, Key Attestation or Not verified, public key.

See Verified events for who verifies what and the daily share.

From Java

Every function on Lyrelog is static from Java, with overloads for the optional arguments:

Lyrelog.start(this, new Configuration("lyr_ing_..."));
Lyrelog.info("checkout_done");
Lyrelog.captureError(e, "store");

Configuration and a logger's functions have overloads too, so trailing arguments can be left out (logger.warning("sync_conflict"), logger.warning("sync_conflict", attrs)).

Configuration

OptionDefaultMeaning
apiKeyrequiredThe project's ingest key
endpointhttps://ingest.lyrelog.comThe base URL; a pasted /v1/... path is stripped. https only, http only for localhost and the emulator's 10.0.2.2
consentConsent.GRANTEDPENDING, GRANTED or DENIED
minimumLevelLevel.DEBUGEvents below it never reach the disk
flushIntervalMillis15 sHow often the uploader runs while an Activity is started
maxBatchBytes512 KiBA batch closes at whichever limit comes first (kept within 4 MiB)
maxBatchEvents500At most 2,000
maxDiskBytes20 MBCap on the queue on disk, oldest first
maxEventAgeMillis7 daysOlder queued events are dropped
sessionTimeoutMillis30 minIdle time that starts a new session
environmentdetectedAny valid name, or null
platformandroidAny valid name, or null
appVersionthe app's versionNameSent as resource.app_version
redactedKeysnull: DEFAULT_REDACTED_KEYSKey names to redact; your list replaces the defaults, an empty list turns it off
captureCrashestrueRecord uncaught exceptions, sent on the next launch
attachScreentrueTag events with the current screen
automaticScreensfalseLog screen_viewed for each Activity, named by its class
attesttrueProve the app with Key Attestation so its events arrive verified, once the project lists its package and certificate
mirrorToLogcatfalseAlso print every event to logcat (tag Lyrelog)
storageDirectorynoBackupFilesDir/lyrelogWhere the queue lives

Delivery and limits

Never blocksLogging copies the event and returns; one background writer puts it on disk and never waits on the network.
Survives kills and offlineA queue in noBackupFilesDir/lyrelog, capped at 20 MB and 7 days. What reached the disk survives a crash, a kill or days offline; events still on their way to the writer (milliseconds) are written by the crash handler, or lost if the process is killed outright. The folder is never in a backup, so a restored phone doesn't resend another device's events.
When it sendsEvery 15 s while an Activity is started, and once when the app goes to the background. In the background nothing runs on a timer: what's left goes on the next launch or the next time the app comes to the front.
BatchesUp to 500 events or 512 KiB per request, gzipped. An event over 1 MiB once encoded is dropped and counted.
Retries1 s doubling to 5 min, with full jitter, honoring Retry-After. Any other 4xx drops the batch, a 3xx (a redirect, never followed) drops it, and a revoked key (401, 403) stops sending until the next launch and keeps the events. A batch the server keeps failing while others go through goes to the back, then is dropped.
Monthly quotaWhen a Free organization has used its month's events, the server answers 429. Events stay in the queue on disk and go out once the server takes them again, within the 20 MB and 7 day caps. The SDK logs one warning to logcat, and again only after a batch has been accepted in between.
Drops are visibleEvents lost to the caps become one lyrelog_events_dropped warning (area lyrelog) with the count.
Its own problemsA wrong endpoint, a 404, rejected lines or an endpoint that doesn't answer go once per launch to logcat, tag Lyrelog, at debug level.
ContextApp id (the package name), version name, version code, android, the Android version, the device (Google Pixel 9), locale, environment, platform android, session id (new after 30 min idle) and install id.
SecretsValues under keys whose name is or ends with authorization, cookie, password, token, secret, apikey and the rest of the shared list become "[redacted]", at any depth, before anything is cut.
LimitsLong strings cut on a character boundary, extra attributes counted in lyrelog_dropped_attrs, payloads over 64 KiB summarized as {"lyrelog_truncated": true, "bytes": N, "preview": "..."}.

Change the list with redactedKeys: your list replaces the defaults, and an empty list turns redaction off. To add to it:

Lyrelog.start(this, Configuration(
    apiKey = "lyr_ing_...",
    redactedKeys = Configuration.DEFAULT_REDACTED_KEYS + "pin",
))

Play data safety

For the Play Console's data safety form, declare what your app sends through Lyrelog:

  • App info and performance: Crash logs, Diagnostics (App functionality, and Analytics if you use it that way). Collected, not shared.
  • Device or other IDs: the install id, a random UUID that isn't the advertising id, isn't backed up and is deleted on a denial. Not linked to the person unless you also call setUser.
  • App activity > App interactions: if you log screens (screen_viewed) or taps.
  • Anything else your attrs or payload carry (emails, purchases...), under its own category.

Data is encrypted in transit (https). The server adds the country of the sending address; the address itself isn't stored.