Timber 库到底是做什么的?

What exactly does the Timber library do?

我听说过 Timber 并且正在阅读 github README,但它悄悄地让我感到困惑。

Behavior is added through Tree instances. You can install an instance by calling Timber.plant. Installation of Trees should be done as early as possible. The onCreate of your application is the most logical choice.

什么行为?

This is a logger with a small, extensible API which provides utility on top of Android's normal Log class.

它在 Android 的日志之上还提供了什么?

The DebugTree implementation will automatically figure out from which class it's being called and use that class name as its tag. Since the tags vary, it works really well when coupled with a log reader like Pidcat.

什么是 DebugTree?

There are no Tree implementations installed by default because every time you log in production, a puppy dies.

同样,什么是树实现?它有什么作用?我该如何停止杀死小狗?

Two easy steps:

Install any Tree instances you want in the onCreate of your application class.

Call Timber's static methods everywhere throughout your app.

完成什么的两个简单步骤?

None 这在自述文件中已经解释过了。对于已经知道它是什么的人来说,这几乎是一个描述:/

问题:-

我们不想在已签名的应用程序中打印日志,因为我们有时可能会记录敏感信息。通常为了克服这个问题,开发人员倾向于在写 log

之前写 if 条件

示例:-

 if(BuildConfig.DEBUG) {
      Log.d(TAG,userName);
  }

所以每次你想打印日志时,你都需要写一个if条件和一个TAG,大多数时候都是class name

木材解决了这两个问题

您只需要在应用程序中检查一次条件 class 并初始化 Timber.plant

class MyApplication : Application() {

override fun onCreate() {
    super.onCreate()

    if (BuildConfig.DEBUG) {
        Timber.plant(DebugTree())
     }
 }

} 

剩下的所有地方我们可以只写 Timber.d("Message") 没有任何标签或 if 条件 .

如果你想要不同的标签,那么你可以使用

  Timber.tag("Tag").d("message");

编辑:

您还可以在 Timber 中种植自己的树,并做一些很酷的事情,例如在发布时仅记录警告和错误,将警告和错误日志发送到服务器等。例如

import timber.log.Timber;

public class ReleaseTree extends Timber.Tree {
  @Override 
  protected void log(int priority, String tag, String message, Throwable t) {

    if (priority == ERROR || priority == WARNING){
      //Send to server
    }

  }
}

您可以为不同的构建风格种植不同的树。

看看这个article and have a listen to this podcast