內容目錄

Timber 概述

Timber 是由 Jake Wharton 開發的函式庫,用來取代內建的 Log。

內建的 Log 需要指定標籤 (tag),但是 Timber 預設是用 activity 的名稱來當做標籤,當然你也可以自訂標籤名稱

Log.d("TAG", "log message")
Timber.d("log message")

Timber.tag("TAG").d("log message")

函式庫相性

app/build.gradle

...
dependencies {
    ...   
    implementation "com.jakewharton.timber:timber:5.0.1"
}

程式碼

我們通常會自訂 Application ,並在其中設定好 Timber

MyApplication.kt

我們通常只需要在 debug 時印出 log

class MyApplication: Application() {
    override fun onCreate() {
        super.onCreate()
	if(BuildConfig.DEBUG) {
	    Timber.plant(Timber.DebugTree())
	}
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="<http://schemas.android.com/apk/res/android>"
    xmlns:tools="<http://schemas.android.com/tools>">

    <application
        android:name=".MyApplication"
				...
    </application>

</manifest>

MainActivity.kt

然後你就可以在程式裏的任何地方使用 Timber ,在這裏以 MainActivity 為例

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
	setContentView(R.layout.activity_main)
	
        Timber.d("onCreate")
    }
}

Reference

User Guide: Write and View Logs with Logcat

User Guide: Logcat command-line tool

Timber的使用与分析

Day 30 – Timber與謝幕

Better Logging In Android Using Timber

https://jimmy4302001.medium.com/使用timber來幫忙打印log-afc54aaa76d6

https://www.section.io/engineering-education/planting-timber-logs-the-right-way/

https://www.freecodecamp.org/news/how-to-log-more-efficiently-with-timber-a3f41b193940/

Android: a library to write log on file?

Github: Treessence

Android Kotlin: Android Writing Logs to text File (help DEV find BUG when TESTER test)

https://stackoverflow.com/questions/1756296/android-writing-logs-to-text-file

File Logging in Android with Timber

Android Writing Logs to text File

Last modified: 2023 年 3 月 16 日

Author

Comments

Write a Reply or Comment

Your email address will not be published.