package com.xuqm.sdk.bugcollect import com.xuqm.sdk.XuqmSDK object BugCollect { private var logLevel: LogLevel = LogLevel.WARN private var environment: String = "production" @Volatile private var queue: LogQueue? = null @Volatile private var crashCaptureStarted = false fun setLogLevel(level: LogLevel) { logLevel = level } fun setEnvironment(env: String) { environment = env } fun event(name: String, properties: Map = emptyMap()) { if (!isReady()) return queue().push(LogEvent( name = name, properties = properties, appKey = XuqmSDK.appKey, userId = XuqmSDK.getUserId(), platform = "android", appVersion = appVersion(), environment = environment, )) FunnelTracker.track(name, properties) } fun captureError(error: Throwable, metadata: Map = emptyMap()) { if (!isReady()) return queue().push(IssueEvent( type = "android_error", message = error.message ?: error.javaClass.name, stack = error.stackTraceToString(), fingerprint = Fingerprint.compute("error", error.message ?: "", error.stackTraceToString()), appKey = XuqmSDK.appKey, userId = XuqmSDK.getUserId(), platform = "android", appVersion = appVersion(), metadata = metadata, environment = environment, )) } fun warn(message: String, metadata: Map = emptyMap()) { if (logLevel.ordinal > LogLevel.WARN.ordinal) return captureError(Exception(message), metadata + ("level" to "warn")) } fun info(message: String, metadata: Map = emptyMap()) { if (logLevel.ordinal > LogLevel.INFO.ordinal) return event("__log_info", metadata + ("message" to message)) } fun startCrashCapture() { if (crashCaptureStarted) return val bugCollectApiUrl = XuqmSDK.bugCollectApiUrl ?: return crashCaptureStarted = true CrashCapture.start( logApiUrl = bugCollectApiUrl, appKey = XuqmSDK.appKey, getUserId = { XuqmSDK.getUserId() }, ) queue().uploadPendingCrashes() } fun defineFunnel(id: String, steps: List) { FunnelTracker.define(id, steps) } private fun isReady() = XuqmSDK.isInitialized() && XuqmSDK.bugCollectEnabled private fun queue(): LogQueue { return queue ?: synchronized(this) { queue ?: LogQueue( logApiUrl = XuqmSDK.bugCollectApiUrl ?: "", appKey = XuqmSDK.appKey, appContext = XuqmSDK.appContext, ).also { queue = it } } } private fun appVersion(): String = runCatching { val ctx = XuqmSDK.appContext ctx.packageManager.getPackageInfo(ctx.packageName, 0).versionName ?: "unknown" }.getOrDefault("unknown") }