日志框架Timber使用与源码解析

今天我们一起来看下Android的一个日志框架Timber,这个框架是Android大神JakeWharton作品。Github地址:Timber原生提供的日志Log查看起来比较麻烦,另外也没有提供扩展的功能。Timber是对原生Log框架的封装,但是提供了很好的扩展和使用性。先来看看怎么使用哈。

1.使用

首先在模块'build.gradle'中的dependencies添加依赖:

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

接着在Application或者MainActivity中注册:

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提供的一个内部类,可以在Debug环境下使用。如果不是Debug环境就可以继承Timber.Tree实现自定义的Tree。这个Tree其实就是框架封装Log的地方,提供了一个抽象的借口log进行扩展。

TAG就是给Log增加标签,但是这里不小心会有个坑,先按下不表,后面源码再看。

到这一步TImber就初始化好了,接下来就可以随便玩喽。写了个简单的Demo,点击按钮打印log。


日志框架Timber使用与源码解析_第1张图片
TimberTest.png

点击获取数据按钮的点击事件,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跟系统原生的是一样的,一一对应就好。

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

细心的小伙伴们可能已经发现,之前设置的TAG明明是MainActivity_MVPTest,为什么打印出来的时候TAG是MainActivity?其实在APP每次启动,第一次点击按钮的时候是能打印出一次MainActivity_MVPTest这个TAG的输出的。这个和上面留的那个悬念是一致的。我们接着看源码就知道了。

2.源码分析

Timber这个框架源码其实就只有一个文件Timber.java,有两个内部类,Timber其实就是通过内部抽象类Tree提供了接口,其中DebugTree就是Timber提供了Debug环境下使用的Tree。

public static class DebugTree extends Tree

public static abstract class Tree

优先级我们之前已经提过了,这里就看一下d这个方法,其他方法都是类似的。
跟进去其实就是到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中,逻辑也是比较简单,就是挨个调用每个Tree的d方法。

private static final Tree[] TREE_ARRAY_EMPTY = new Tree[0];
  // Both fields guarded by 'FOREST'.
private static final List 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的共有功能,比如在打印日志之前调用prepareLog格式化输出字符串,
接着就是log这个方法口子了,自定义Tree都需要实现。

public static abstract class Tree{
    final ThreadLocal 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 explicitTag = new ThreadLocal<>();就是每个线程的局部变量。

private static final Tree[] TREE_ARRAY_EMPTY = new Tree[0];
// Both fields guarded by 'FOREST'.
private static final List 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掉了,所以也就导致每次只打印一个设定Tag的日志了。

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

我也没明白大神为什么这么设计,有清楚的小伙伴欢迎留言哈。

Timber中默认实现的DebugTree逻辑中的log中,其实就是判断需不需要换行,然后调用系统原生的Log进行日志打印的工作。

@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逻辑,默认就是当前类的类名。逻辑简单说就是先到父类Tree中取Tag,没有就从调用堆栈中找到当前类,取类名作为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.总结

大神就是大神哈,一个文件就写出了一个扩展性这么好的框架,其实分析源码主要获益的就是源码的设计模式,在Timber中用到了代理模式和接口模式,通过代理模式调用每个用户添加的Tree,然后在统一的父类中做前期工作,比如取Tag和格式化输出字符串等。

今天Timber的分析就到此了,欢迎大家关注和点赞哈。

以上。

欢迎关注公众号:JueCode

你可能感兴趣的:(日志框架Timber使用与源码解析)