日志框架Timber使用與源碼解析

今天我們一起來看下Android的一個日志框架Timber,這個框架是Android大神JakeWharton作品。Github地址:Timber原生提供的日志Log查看起來比較麻煩,另外也沒有提供擴(kuò)展的功能。Timber是對原生Log框架的封裝,但是提供了很好的擴(kuò)展和使用性。先來看看怎么使用哈。

1.使用

首先在模塊'build.gradle'中的dependencies添加依賴:

compile 'com.jakewharton.timber:timber:4.6.0'

接著在Application或者M(jìn)ainActivity中注冊:

if (BuildConfig.DEBUG) {
    Timber.plant(new Timber.DebugTree());
} else {
    Timber.plant(new Timber.Tree() {
        @Override
        protected void log(int priority, String tag, String message, Throwable t) {
            Timber.d(tag, message);
        }
    });
}

Timber.tag(TAG);

private static final String TAG = MainActivity.class.getSimpleName() + "_MVPTest";

Timber.DebugTree是Timber提供的一個內(nèi)部類,可以在Debug環(huán)境下使用。如果不是Debug環(huán)境就可以繼承Timber.Tree實現(xiàn)自定義的Tree。這個Tree其實就是框架封裝Log的地方,提供了一個抽象的借口log進(jìn)行擴(kuò)展。

TAG就是給Log增加標(biāo)簽,但是這里不小心會有個坑,先按下不表,后面源碼再看。

到這一步TImber就初始化好了,接下來就可以隨便玩嘍。寫了個簡單的Demo,點擊按鈕打印log。


TimberTest.png

點擊獲取數(shù)據(jù)按鈕的點擊事件,Timber支持格式化輸出字符串功能:

@Override
public void showData(String data) {
    Timber.d("Timber.d showData OnClick");
    Timber.d("%s be Clicked" , data);
    Timber.i("Timber.i showData OnClick");
    Timber.e("Timber.e showData OnClick");
    text.setText(data);
}

其中d,i,e跟系統(tǒng)原生的是一樣的,一一對應(yīng)就好。

public static final int ASSERT = 7;
public static final int DEBUG = 3;
public static final int ERROR = 6;
public static final int INFO = 4;
public static final int VERBOSE = 2;
public static final int WARN = 5;

看一下打印的效果:


Timber.PNG

細(xì)心的小伙伴們可能已經(jīng)發(fā)現(xiàn),之前設(shè)置的TAG明明是MainActivity_MVPTest,為什么打印出來的時候TAG是MainActivity?其實在APP每次啟動,第一次點擊按鈕的時候是能打印出一次MainActivity_MVPTest這個TAG的輸出的。這個和上面留的那個懸念是一致的。我們接著看源碼就知道了。

2.源碼分析

Timber這個框架源碼其實就只有一個文件Timber.java,有兩個內(nèi)部類,Timber其實就是通過內(nèi)部抽象類Tree提供了接口,其中DebugTree就是Timber提供了Debug環(huán)境下使用的Tree。

public static class DebugTree extends Tree

public static abstract class Tree

優(yōu)先級我們之前已經(jīng)提過了,這里就看一下d這個方法,其他方法都是類似的。
跟進(jìn)去其實就是到TREE_OF_SOULS中了,其他的v,e或者i都是代理給了TREE_OF_SOULS處理。這里用到的就是代理模式了。

public final class Timber{
    /** Log a debug message with optional format args. */
    public static void d(@NonNls String message, Object... args) {
        TREE_OF_SOULS.d(message, args);
    }
}

接著跟到TREE_OF_SOULS中,邏輯也是比較簡單,就是挨個調(diào)用每個Tree的d方法。

private static final Tree[] TREE_ARRAY_EMPTY = new Tree[0];
  // Both fields guarded by 'FOREST'.
private static final List<Tree> FOREST = new ArrayList<>();
static volatile Tree[] forestAsArray = TREE_ARRAY_EMPTY;


private static final Tree TREE_OF_SOULS = new Tree() {

    @Override public void d(String message, Object... args) {
      Tree[] forest = forestAsArray;
      //noinspection ForLoopReplaceableByForEach
      for (int i = 0, count = forest.length; i < count; i++) {
        forest[i].d(message, args);
      }
    }
}

接著再來看下Tree中的代碼,這里就收攏了每個用戶自定義的Tree的共有功能,比如在打印日志之前調(diào)用prepareLog格式化輸出字符串,
接著就是log這個方法口子了,自定義Tree都需要實現(xiàn)。

public static abstract class Tree{
    final ThreadLocal<String> explicitTag = new ThreadLocal<>();

    @Nullable
    String getTag() {
      String tag = explicitTag.get();
      if (tag != null) {
        explicitTag.remove();
      }
      return tag;
    }

    /** Log a debug message with optional format args. */
    public void d(String message, Object... args) {
      prepareLog(Log.DEBUG, null, message, args);
    }

    private void prepareLog(int priority, Throwable t, String message, Object... args) {
      // Consume tag even when message is not loggable so that next message is correctly tagged.
      String tag = getTag();

      if (!isLoggable(tag, priority)) {
        return;
      }
      if (message != null && message.length() == 0) {
        message = null;
      }
      if (message == null) {
        if (t == null) {
          return; // Swallow message if it's null and there's no throwable.
        }
        message = getStackTraceString(t);
      } else {
        if (args != null && args.length > 0) {
          message = formatMessage(message, args);
        }
        if (t != null) {
          message += "\n" + getStackTraceString(t);
        }
      }

      log(priority, tag, message, t);
    }

    protected abstract void log(int priority, @Nullable String tag, @NotNull String message,
        @Nullable Throwable t);
}

上面分析了整個工作流程。那么上面留的疑問是怎么回事?這個就要從添加Tag的步驟說起。其實邏輯很簡單就是給每個Tree添加Tag。
其中final ThreadLocal<String> explicitTag = new ThreadLocal<>();就是每個線程的局部變量。

private static final Tree[] TREE_ARRAY_EMPTY = new Tree[0];
// Both fields guarded by 'FOREST'.
private static final List<Tree> FOREST = new ArrayList<>();
static volatile Tree[] forestAsArray = TREE_ARRAY_EMPTY;

public final class Timber{
    @NotNull
    public static Tree tag(String tag) {
        Tree[] forest = forestAsArray;
        //noinspection ForLoopReplaceableByForEach
        for (int i = 0, count = forest.length; i < count; i++) {
            forest[i].explicitTag.set(tag);
        }
        return TREE_OF_SOULS;
    }
}

存放的邏輯我們知道了,再看看是怎么取的。取的邏輯肯定就是在抽象類Tree中,這就比較清晰了,每次取出來之后就remove掉了,所以也就導(dǎo)致每次只打印一個設(shè)定Tag的日志了。

public static abstract class Tree {
    @Nullable
    String getTag() {
      String tag = explicitTag.get();
      if (tag != null) {
        explicitTag.remove();
      }
      return tag;
    }
}

我也沒明白大神為什么這么設(shè)計,有清楚的小伙伴歡迎留言哈。

Timber中默認(rèn)實現(xiàn)的DebugTree邏輯中的log中,其實就是判斷需不需要換行,然后調(diào)用系統(tǒng)原生的Log進(jìn)行日志打印的工作。

@Override protected void log(int priority, String tag, @NotNull String message, Throwable t) {
      if (message.length() < MAX_LOG_LENGTH) {
        if (priority == Log.ASSERT) {
          Log.wtf(tag, message);
        } else {
          Log.println(priority, tag, message);
        }
        return;
      }

      // Split by line, then ensure each line can fit into Log's maximum length.
      for (int i = 0, length = message.length(); i < length; i++) {
        int newline = message.indexOf('\n', i);
        newline = newline != -1 ? newline : length;
        do {
          int end = Math.min(newline, i + MAX_LOG_LENGTH);
          String part = message.substring(i, end);
          if (priority == Log.ASSERT) {
            Log.wtf(tag, part);
          } else {
            Log.println(priority, tag, part);
          }
          i = end;
        } while (i < newline);
      }
}

再看看DebugTree的Tag邏輯,默認(rèn)就是當(dāng)前類的類名。邏輯簡單說就是先到父類Tree中取Tag,沒有就從調(diào)用堆棧中找到當(dāng)前類,取類名作為Tag。

@Nullable
protected String createStackElementTag(@NotNull StackTraceElement element) {
      String tag = element.getClassName();
      Matcher m = ANONYMOUS_CLASS.matcher(tag);
      if (m.find()) {
        tag = m.replaceAll("");
      }
      tag = tag.substring(tag.lastIndexOf('.') + 1);
      // Tag length limit was removed in API 24.
      if (tag.length() <= MAX_TAG_LENGTH || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return tag;
      }
      return tag.substring(0, MAX_TAG_LENGTH);
}

@Override final String getTag() {
      String tag = super.getTag();
      if (tag != null) {
        return tag;
      }

      // DO NOT switch this to Thread.getCurrentThread().getStackTrace(). The test will pass
      // because Robolectric runs them on the JVM but on Android the elements are different.
      StackTraceElement[] stackTrace = new Throwable().getStackTrace();
      if (stackTrace.length <= CALL_STACK_INDEX) {
        throw new IllegalStateException(
            "Synthetic stacktrace didn't have enough elements: are you using proguard?");
      }
      return createStackElementTag(stackTrace[CALL_STACK_INDEX]);
}

3.總結(jié)

大神就是大神哈,一個文件就寫出了一個擴(kuò)展性這么好的框架,其實分析源碼主要獲益的就是源碼的設(shè)計模式,在Timber中用到了代理模式和接口模式,通過代理模式調(diào)用每個用戶添加的Tree,然后在統(tǒng)一的父類中做前期工作,比如取Tag和格式化輸出字符串等。

今天Timber的分析就到此了,歡迎大家關(guān)注和點贊哈。

以上。

歡迎關(guān)注公眾號:JueCode

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容