Timber

Timber原意是木材,JakeWharton大神编写的Log库,对安卓的Log进行了一层封装,让Log的处理以列表的方式处理。

核心类为Tree,Tree封装了常用的log等级

  /** A facade for handling logging calls. Install instances via {@link #plant Timber.plant()}. */
  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 verbose message with optional format args. */
    public void v(String message, Object... args) {
      prepareLog(Log.VERBOSE, null, message, args);
    }

    /** Log a verbose exception and a message with optional format args. */
    public void v(Throwable t, String message, Object... args) {
      prepareLog(Log.VERBOSE, t, message, args);
    }

    /** Log a verbose exception. */
    public void v(Throwable t) {
      prepareLog(Log.VERBOSE, t, null);
    }

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

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

    /** Log a debug exception. */
    public void d(Throwable t) {
      prepareLog(Log.DEBUG, t, null);
    }

    /** Log an info message with optional format args. */
    public void i(String message, Object... args) {
      prepareLog(Log.INFO, null, message, args);
    }

    /** Log an info exception and a message with optional format args. */
    public void i(Throwable t, String message, Object... args) {
      prepareLog(Log.INFO, t, message, args);
    }

    /** Log an info exception. */
    public void i(Throwable t) {
      prepareLog(Log.INFO, t, null);
    }

    /** Log a warning message with optional format args. */
    public void w(String message, Object... args) {
      prepareLog(Log.WARN, null, message, args);
    }

    /** Log a warning exception and a message with optional format args. */
    public void w(Throwable t, String message, Object... args) {
      prepareLog(Log.WARN, t, message, args);
    }

    /** Log a warning exception. */
    public void w(Throwable t) {
      prepareLog(Log.WARN, t, null);
    }

    /** Log an error message with optional format args. */
    public void e(String message, Object... args) {
      prepareLog(Log.ERROR, null, message, args);
    }

    /** Log an error exception and a message with optional format args. */
    public void e(Throwable t, String message, Object... args) {
      prepareLog(Log.ERROR, t, message, args);
    }

    /** Log an error exception. */
    public void e(Throwable t) {
      prepareLog(Log.ERROR, t, null);
    }

    /** Log an assert message with optional format args. */
    public void wtf(String message, Object... args) {
      prepareLog(Log.ASSERT, null, message, args);
    }

    /** Log an assert exception and a message with optional format args. */
    public void wtf(Throwable t, String message, Object... args) {
      prepareLog(Log.ASSERT, t, message, args);
    }

    /** Log an assert exception. */
    public void wtf(Throwable t) {
      prepareLog(Log.ASSERT, t, null);
    }

    /** Log at {@code priority} a message with optional format args. */
    public void log(int priority, String message, Object... args) {
      prepareLog(priority, null, message, args);
    }

    /** Log at {@code priority} an exception and a message with optional format args. */
    public void log(int priority, Throwable t, String message, Object... args) {
      prepareLog(priority, t, message, args);
    }

    /** Log at {@code priority} an exception. */
    public void log(int priority, Throwable t) {
      prepareLog(priority, t, null);
    }

    /**
     * Return whether a message at {@code priority} should be logged.
     * @deprecated use {@link #isLoggable(String, int)} instead.
     */
    @Deprecated
    protected boolean isLoggable(int priority) {
      return true;
    }

    /** Return whether a message at {@code priority} or {@code tag} should be logged. */
    protected boolean isLoggable(@Nullable String tag, int priority) {
      //noinspection deprecation
      return isLoggable(priority);
    }

    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);
    }

    /**
     * Formats a log message with optional arguments.
     */
    protected String formatMessage(@NotNull String message, @NotNull Object[] args) {
      return String.format(message, args);
    }

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

    /**
     * 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, @Nullable String tag, @NotNull String message,
        @Nullable Throwable t);
  }

通过plant()方法添加一个Tree,这个Tree会被添加到名为FOREST的列表中,并且会同步到forestAsArray这个数组中

  /** Add a new logging tree. */
  @SuppressWarnings("ConstantConditions") // Validating public API contract.
  public static void plant(@NotNull 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()]);
    }
  }

  /** Adds new logging trees. */
  @SuppressWarnings("ConstantConditions") // Validating public API contract.
  public static void plant(@NotNull Tree... trees) {
    if (trees == null) {
      throw new NullPointerException("trees == null");
    }
    for (Tree tree : trees) {
      if (tree == null) {
        throw new NullPointerException("trees contains null");
      }
      if (tree == TREE_OF_SOULS) {
        throw new IllegalArgumentException("Cannot plant Timber into itself.");
      }
    }
    synchronized (FOREST) {
      Collections.addAll(FOREST, trees);
      forestAsArray = FOREST.toArray(new Tree[FOREST.size()]);
    }
  }

我们调用Timber.v 等log方法的时候,底层是通过TREE_OF_SOULS代理的,TREE_OF_SOULS是Tree的实现类,代理方法会遍历forestAsArray数组,执行注册的每一个Tree对应的方法

  /** A {@link Tree} that delegates to all planted trees in the {@linkplain #FOREST forest}. */
  private static final Tree TREE_OF_SOULS = new Tree() {
    @Override public void v(String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.v(message, args);
      }
    }

    @Override public void v(Throwable t, String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.v(t, message, args);
      }
    }

    @Override public void v(Throwable t) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.v(t);
      }
    }

    @Override public void d(String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.d(message, args);
      }
    }

    @Override public void d(Throwable t, String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.d(t, message, args);
      }
    }

    @Override public void d(Throwable t) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.d(t);
      }
    }

    @Override public void i(String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.i(message, args);
      }
    }

    @Override public void i(Throwable t, String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.i(t, message, args);
      }
    }

    @Override public void i(Throwable t) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.i(t);
      }
    }

    @Override public void w(String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.w(message, args);
      }
    }

    @Override public void w(Throwable t, String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.w(t, message, args);
      }
    }

    @Override public void w(Throwable t) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.w(t);
      }
    }

    @Override public void e(String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.e(message, args);
      }
    }

    @Override public void e(Throwable t, String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.e(t, message, args);
      }
    }

    @Override public void e(Throwable t) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.e(t);
      }
    }

    @Override public void wtf(String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.wtf(message, args);
      }
    }

    @Override public void wtf(Throwable t, String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.wtf(t, message, args);
      }
    }

    @Override public void wtf(Throwable t) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.wtf(t);
      }
    }

    @Override public void log(int priority, String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.log(priority, message, args);
      }
    }

    @Override public void log(int priority, Throwable t, String message, Object... args) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.log(priority, t, message, args);
      }
    }

    @Override public void log(int priority, Throwable t) {
      Tree[] forest = forestAsArray;
      for (Tree tree : forest) {
        tree.log(priority, t);
      }
    }

    @Override protected void log(int priority, String tag, @NotNull String message, Throwable t) {
      throw new AssertionError("Missing override for log method.");
    }
  };

DebugTree,Timber默认实现的用于debug包输入日志的Tree

  /** A {@link Tree Tree} for debug builds. Automatically infers the tag from the calling class. */
  public static class DebugTree extends Tree {
    private static final int MAX_LOG_LENGTH = 4000;
    private static final int MAX_TAG_LENGTH = 23;
    private static final int CALL_STACK_INDEX = 5;
    private static final Pattern ANONYMOUS_CLASS = Pattern.compile("(\\$\\d+)+$");

    /**
     * Extract the tag which should be used for the message from the {@code element}. By default
     * this will use the class name without any anonymous class suffixes (e.g., {@code Foo$1}
     * becomes {@code Foo}).
     * <p>
     * Note: This will not be called if a {@linkplain #tag(String) manual tag} was specified.
     */
    @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]);
    }

    /**
     * Break up {@code message} into maximum-length chunks (if needed) and send to either
     * {@link Log#println(int, String, String) Log.println()} or
     * {@link Log#wtf(String, String) Log.wtf()} for logging.
     *
     * {@inheritDoc}
     */
    @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);
      }
    }
  }

其中有个自动推断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]);

还有个Throwable转String的方法:

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

其他方法:
tag(String tag):设置之后的Log的tag

  /** Set a one-time tag for use on the next logging call. */
  @NotNull
  public static Tree tag(String tag) {
    Tree[] forest = forestAsArray;
    for (Tree tree : forest) {
      tree.explicitTag.set(tag);
    }
    return TREE_OF_SOULS;
  }

uproot(@NotNull Tree tree):移除一个Tree

  /** Remove a planted tree. */
  public static void uproot(@NotNull Tree tree) {
    synchronized (FOREST) {
      if (!FOREST.remove(tree)) {
        throw new IllegalArgumentException("Cannot uproot tree which is not planted: " + tree);
      }
      forestAsArray = FOREST.toArray(new Tree[FOREST.size()]);
    }
  }

uprootAll():移除所有Tree

  /** Remove all planted trees. */
  public static void uprootAll() {
    synchronized (FOREST) {
      FOREST.clear();
      forestAsArray = TREE_ARRAY_EMPTY;
    }
  }

forest():返回所有包含所有Tree的复制列表(该列表不能编辑):

  /** Return a copy of all planted {@linkplain Tree trees}. */
  @NotNull
  public static List<Tree> forest() {
    synchronized (FOREST) {
      return unmodifiableList(new ArrayList<>(FOREST));
    }
  }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容