萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 方便的日誌工具類:LogCat、堆疊追蹤字串化與檔案落地

前言

Android 內建 android.util.Log 提供 v/d/i/w/e/wtf 五級日誌,但僅輸出至 Logcat (環狀緩衝區),重啟即丟失。生產環境常需將錯誤堆疊持久化至檔案或上傳伺服器。本文介紹 Log.getStackTraceString(Throwable) 字串化技巧,並提供完整落地檔案/上傳工具類。

核心 API

// 將 Throwable 完整堆疊轉為字串 (含原因鏈)
val stackTraceString = Log.getStackTraceString(throwable)

// 等價於
val writer = StringWriter()
throwable.printStackTrace(PrintWriter(writer))
writer.toString()

完整日誌工具類 (Kotlin)

object Logger {
    private const val MAX_FILE_SIZE = 2 * 1024 * 1024 // 2MB
    private const val MAX_FILES = 5

    private val logDir: File by lazy { 
        File(context.cacheDir, "logs").apply { mkdirs() } 
    }

    @Volatile private var currentFile: File? = null
    @Volatile private var currentSize = 0L

    fun init(context: Context) { /* 可選:初始化上傳配置 */ }

    fun d(tag: String, msg: String) = log(Log.DEBUG, tag, msg, null)
    fun i(tag: String, msg: String) = log(Log.INFO, tag, msg, null)
    fun w(tag: String, msg: String, tr: Throwable? = null) = log(Log.WARN, tag, msg, tr)
    fun e(tag: String, msg: String, tr: Throwable? = null) = log(Log.ERROR, tag, msg, tr)

    private fun log(priority: Int, tag: String, msg: String, tr: Throwable?) {
        val timestamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault()).format(Date())
        val thread = Thread.currentThread().name
        val fullMsg = "$timestamp [$thread] $msg${tr?.let { "\n" + Log.getStackTraceString(it) } ?? ""}"

        // 1. Logcat
        android.util.Log.println(priority, tag, fullMsg)

        // 2. 落地檔案 (非 UI 執行緒)
        CoroutineScope(Dispatchers.IO).launch {
            rotateIfNeeded()
            currentFile?.appendText("$fullMsg\n")
            currentSize += fullMsg.length.toLong()
        }

        // 3. 可選:上傳至遠端 (Sentry, Bugsnag, 自建)
        // if (priority >= Log.ERROR) RemoteLogger.upload(tag, fullMsg)
    }

    private fun rotateIfNeeded() {
        if (currentFile == null || currentSize > MAX_FILE_SIZE) {
            val time = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            currentFile = File(logDir, "app_$time.log")
            currentSize = 0
            // 刪除舊檔
            logDir.listFiles()?.sortedByDescending { it.lastModified() }?.drop(MAX_FILES)?.forEach { it.delete() }
        }
    }

    // 取得所有日誌檔供用戶分享/上傳
    fun getLogFiles(): List = logDir.listFiles()?.sortedByDescending { it.lastModified() }?.toList() ?: emptyList()
}

使用範例

try {
    riskyOperation()
} catch (e: Exception) {
    Logger.e("Network", "API 請求失敗", e)
    // 檔案已在背景寫入,可在「設定→意見回饋」附上 Logger.getLogFiles()
}

進階整合建議

  • Timber:流行封裝庫,支援 DebugTree (Logcat) + ReleaseTree (上傳/加密/壓縮),一行 Timber.plant() 完成切換。
  • Sentry / Bugsnag / Firebase Crashlytics:自動捕獲未處理例外、附帶裝置資訊、麵包屑、版本關聯。
  • 加密日誌:若日誌含敏感資訊 (Token、PII),落地前請用 AES-GCM 加密,金鑰存 Keystore。
  • 隱私合規:Data Safety Section 宣告收集日誌、用途、保留期限;提供使用者「匯出/刪除我的日誌」功能。

常見誤區

Q: 直接在主執行緒寫檔案可以嗎?
A: 會導致 UI 卡頓,務必切至 IO 執行緒 (Coroutine Dispatchers.IO / RxJava Schedulers.io / ThreadPool)。
Q: Logcat 緩衝區多大?
A: 通常 256KB~1MB (視裝置),舊日誌會被覆蓋,**不可依賴 Logcat 做審計**。

結合 Log.getStackTraceString、非同步落地檔案、雲端上報,構建完整可觀測體系。

copyright © 萬盛學電腦網 all rights reserved