Android 內建 android.util.Log 提供 v/d/i/w/e/wtf 五級日誌,但僅輸出至 Logcat (環狀緩衝區),重啟即丟失。生產環境常需將錯誤堆疊持久化至檔案或上傳伺服器。本文介紹 Log.getStackTraceString(Throwable) 字串化技巧,並提供完整落地檔案/上傳工具類。
// 將 Throwable 完整堆疊轉為字串 (含原因鏈)
val stackTraceString = Log.getStackTraceString(throwable)
// 等價於
val writer = StringWriter()
throwable.printStackTrace(PrintWriter(writer))
writer.toString()
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.plant() 完成切換。結合 Log.getStackTraceString、非同步落地檔案、雲端上報,構建完整可觀測體系。