Timber源码解析及涉及知识点总结

简介

Timber是基于Android源生Log类的封装库,只有一个类几百行代码,但其源码中依然有很多知识点值得总结记录。Github
Timber类如同它的类注释所写:

/** Logging for lazy people. */
public final class Timber {...}

是为懒人准备的,其一个重要功能是在打log的时候可以省略tag,Timber默认会获取打印log语句所在类的类名作为tag。本文基于Timber版本4.5.1,介绍一下使用方法,分析一下源码,并对源码中的知识点做一个总结。

使用方法

  • 安装
    compile'com.jakewharton.timber:timber:4.5.1'
  • 种树
    在项目Application类的onCreate方法中调用Timber的plant方法,传入抽象类Tree的子类实例,可以叫做种树。DebugTree类是Tree 类的一个简单实现。也可以继承Tree类实现自己的需求。
public class ExampleApp extends Application {
  @Override public void onCreate() {
    super.onCreate();

    if (BuildConfig.DEBUG) {
      Timber.plant(new DebugTree());
    } else {
      //生产环境下种不同的树
    }
  }
}
  • 打log
    在任何地方调用Timber的静态方法即可,例如:Timber.d("test");

源码分析

Timber.d("test");中的d方法进入源码,看一下实现的流程。可以看到Timber中有很多同静态方法d类似的v、d、i、w、e和对应assert的wtf方法及重载方法。他们的实现都是调用了TREE_OF_SOULS的相应方法。

  /** A {@link Tree} that delegates to all planted trees in the {@linkplain #FOREST forest}. */
  private static final Tree TREE_OF_SOULS = new Tree() {...}

TREE_OF_SOULS是Tree类的子类对象,类注释写着这棵特殊的树代表了所有在森林(FOREST对象)里种植过的树,等会再解释先来看看父类Tree这个抽象类。

  /** A facade for handling logging calls. Install instances via {@link #plant Timber.plant()}. */
  public static abstract class Tree {...}

这里使用了facade模式。Tree类是外观类,通过plant方法Timber持有Tree类的实例,Timber中的asTree、tag方法将它暴露出去,而对于调用者来说依赖的是抽象类Tree,而不是具体的Tree的实现,如果要更换或者添加Tree类实例,只需要调用plant等相关方法即可,所有调用者使用Tree对象的地方不需要做任何修改,这是符合面向对象依赖倒置原则的一个很好的体现。

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

Tree里的d方法和其他v、i、w、e等方法都调用了私有方法prepareLog。

    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.length > 0) {
          message = formatMessage(message, args);
        }
        if (t != null) {
          message += "\n" + getStackTraceString(t);
        }
      }

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

prepareLog中判断了是否可以打log,处理了要打印打的message信息,最后调用了protected abstract void log(int priority, String tag, String message, Throwable t)方法,可以看到其他log的重载方法也是调用了prepareLog,最终也调用了这个方法。

   /**
     * Write a log message to its destination. Called for all level-specific methods by default.
     *
     * @param priority Log level. See {@link Log} for constants.
     * @param tag Explicit or inferred tag. May be {@code null}.
     * @param message Formatted log message. May be {@code null}, but then {@code t} will not be.
     * @param t Accompanying exceptions. May be {@code null}, but then {@code message} will not be.
     */
    protected abstract void log(int priority, String tag, String message, Throwable t);

这个四个参数的log方法是Tree类中唯一一个待实现的抽象方法,也就是根据传入的参数来执行具体打印的地方。

接下来看看TREE_OF_SOULS的d方法和log方法是如何实现的。

    @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);
      }
    }
    @Override protected void log(int priority, String tag, String message, Throwable t) {
      throw new AssertionError("Missing override for log method.");
    }

TREE_OF_SOULS实现的log方法不承担打印的工作且不能被调用,d方法重写了父类的d方法,遍历了forestAsArray,调用了其中每个元素的d方法。
forestAsArray是什么?

  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;
  /** Add a new logging tree. */
  public static void plant(Tree tree) {
    if (tree == null) {
      throw new NullPointerException("tree == null");
    }
    if (tree == TREE_OF_SOULS) {
      throw new IllegalArgumentException("Cannot plant Timber into itself.");
    }
    synchronized (FOREST) {
      FOREST.add(tree);
      forestAsArray = FOREST.toArray(new Tree[FOREST.size()]);
    }
  }

Timber类持有了一个List对象FOREST(森林),在plant、uproot、uprootAll等方法里面对它进行了增减的操作,它是线程安全的,每次FOREST内容变动,都会生成一个对应的新的Tree数组,而forestAsArray就是这个数组的引用。由Timber.plant传入的Tree实例,被保存在forestAsArray中,TREE_OF_SOULS的d方法调用了所有传入Tree实例的d方法,其他v、i、w、e等方法也一样,这也就是前面提到的TREE_OF_SOULS类注释”这棵树代表了所有在森林里种植过的树“的含义。
接下来就看看DebugTree这棵树的实现,log方法中根据设定的MAX_LOG_LENGTH进行了分行打印,获取调用类名为tag名部分在getTag方法中。

    @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();

      for(StackTraceElement element:stackTrace){
        System.out.println(element);
      }
      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]);
    }

首先调用了Tree的getTag方法。

    final ThreadLocal explicitTag = new ThreadLocal<>();

    String getTag() {
      String tag = explicitTag.get();
      if (tag != null) {
        explicitTag.remove();
      }
      return tag;
    }
  /** Set a one-time tag for use on the next logging call. */
  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;
  }

父类的getTag返回的是调用tag方法设置的值,而且if (tag != null) {explicitTag.remove();}在使用过一次之后就会被清除,这里使用了ThreadLocal来保证所有线程拥有自己独立的tag副本。回到DebugTree的getTag方法,如果没有手动设置tag,那么获取了堆栈信息来确立tag。CALL_STACK_INDEX = 5的原因如图:

Timber源码解析及涉及知识点总结_第1张图片
屏幕快照 2017-10-26 上午11.32.41.png

MainActivity的run方法143行
调用了Timber.d
调用了TREE_OF_SOULS.d
调用了DebugTree.d也就是Tree的d
调用了prepareLog
调用了getTag

所以图片中自上而下由0开始,到MainActivity调用Timber.d打印log的地方,处于堆栈数组的第六位,CALL_STACK_INDEX = 5。

总结知识点

  • 工具类常有的写法,私有构造方法,防止被错误的实例化使用。
  private Timber() {
    throw new AssertionError("No instances.");
  }
  • 外观模式的使用,前面也提到了。Tree类为外观类,TREE_OF_SOULS、DebugTree为子类,对外隐藏实现细节。
  • synchronized的使用,以FOREST为锁。
  • volatile的使用,保证了多线程读取的安全性。还有可以发现很多方法里用到Tree[] forest = forestAsArray;,是因为forestAsArray可能会改变。如果直接使用forestAsArray来遍历,一个线程遍历时,如果在其他线程调用了plant等方法改变了forestAsArray,就会导致异常,使用volatile和局部变量,避免了用锁同步,提高了效率。
  • TREE_ARRAY_EMPTY,有几个地方使用了new Tree[0],为了减少对象创建,使用TREE_ARRAY_EMPTY引用new Tree[0],对效率的追求可见一斑。
  • for循环,建立临时变量count以内存空间换取运行时间,追求效率。
      for (int i = 0, count = forest.length; i < count; i++) {
            ...
      }
  • ThreadLocal的使用,避免了线程安全问题。
  • 获取堆栈信息
    private String getStackTraceString(Throwable t) {
      // Don't replace this with Log.getStackTraceString() - it hides
      // UnknownHostException, which is not what we want.
      StringWriter sw = new StringWriter(256);
      PrintWriter pw = new PrintWriter(sw, false);
      t.printStackTrace(pw);
      pw.flush();
      return sw.toString();
    }

注释解释了如果使用Log.getStackTraceString()会看不到UnknownHostException。

  • 正则表达式
  • tag长度限制,在API 24以前,tag的长度最大只能到23。
      private static final int MAX_TAG_LENGTH = 23;

      // Tag length limit was removed in API 24.
      if (tag.length() <= MAX_TAG_LENGTH || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return tag;
      }
  • StackTraceElement类的使用,获取方式的区别,注释解释了Thread.getCurrentThread().getStackTrace()会有不同的结果。
      // 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();
  • 注释的添加,public的一定有注释,有歧义的地方写注释,为看代码的人节省了很多时间。

结语

可以看到很多地方做了提高效率的细节处理,在此整理做个记录,还写不出来考虑这么周详的代码,但是这会是一直追求的方向。

你可能感兴趣的:(Timber源码解析及涉及知识点总结)