Timber

Timber初始化设置。

        Timber.plant(new Timber.DebugTree());

        Timber.plant(new Timber.DebugTree() {
            @Override
            protected void log(int priority, String tag, @NotNull String message, Throwable t) {
//                super.log(priority, tag, message, t);
                switch (priority) {
                    case Log.DEBUG:
                        ILog.d(tag, message);
                        break;
                    case Log.INFO:
                        ILog.i(tag, message);
                        break;
                    case Log.WARN:
                        ILog.w(tag, message);
                        break;
                    case Log.ERROR:
                        ILog.e(tag, message);
                        break;
                    case Log.ASSERT:
                        ILog.a(tag, message);
                        break;
                    case Log.VERBOSE:
                        ILog.v(tag, message);
                        break;

                }
            }

        });
        
       Logger.addLogAdapter(new AndroidLogAdapter());
		Timber.plant(new Timber.DebugTree() {
			@Override
			protected void log(int priority, String tag, String message, Throwable t) {
				Logger.log(priority, tag, message, t);
			}

		});

可以要设置一般是设置 log(int priority, String tag, @NotNull String message, Throwable t)的方法。里面的super.log(priority, tag, message, t);是显示控制台打印,如果你加入的log框架里面已经有控制打印可以不用,要不然你每次都会看到两行一模一样的log信息打印出来。Timber.plant可以加多几个log框架来控制。

Timeber调用方法。

        Timber.tag(TAG).d("ddddd");
        Timber.tag(TAG).i("iii");
        Timber.tag(TAG).v("vvv");
        Timber.tag(TAG).e("eeee");
        Timber.tag(TAG).w("wwww");
        String mac = getMacFromHardware();
        Timber.tag(TAG).i("mac: " + mac);
        Timber.i("mac: " + mac);

Timeber打印log大致有两种方式。一种是像Timber.tag(TAG).i("iii");这样的,另外一种是不加tag的Timber.i("mac: " + mac);这种tag是自动获取的,下面会讲到getStackTrace的方式获取。

下面来看Timber.i会调用到什么东西。

    public static void d(Throwable t, @NonNls String message, Object... args) {
    TREE_OF_SOULS.d(t, message, args);
  }
  
  public static void i(Throwable t, @NonNls String message, Object... args) {
    TREE_OF_SOULS.i(t, message, args);
  }
  
    public static void wtf(Throwable t, @NonNls String message, Object... args) {
    TREE_OF_SOULS.wtf(t, message, args);
  }
  

TREE_OF_SOULS是一个总调的方式,里面调用的是各种log策略。
在Timber的变量来看。TREE_OF_SOULS里面各个方法用遍历的方式查询和调用各种log策略。

       //空的tree,主要是清空的时候用。
	  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;// 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 protected void log(int priority, String tag, @NotNull String message, Throwable t) {
      throw new AssertionError("Missing override for log method.");
    }
  };
//不让创建,作为工具类用。
  private Timber() {
    throw new AssertionError("No instances.");
  }

设置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;
  }

这个是上面调用Timber.tag设置的Tag。explicitTag是对应到Tree里面的ThreadLocal。

下面这个是Tree的类。可以看到explicitTag和getTag是和tag设置是有关的。然后下面各个等级的日记调用都是调用prepareLog。

  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 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);
    }
   ......
        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();
//这里是设置限制log信息打印的,可以更改该方法下的返回值来控制。
      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);
   }

prepareLog是整理log信息用的,把可能的Throwable和Message整理在一起。

好了,下面看下plant方法是这么调用的。

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

plant是设置各种策略用的,它的目的是把策略保存在一个数列中,FOREST和forestAsArray。

DebugTree类是里面提供的一个参考类。

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

//获取tag信息。判断是否有tag信息,如果没有则创建一个。
    @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);
      }
    }
  }

DebugTree类提供了一个控制台打印的方式。可以通过集成该类修改log(int priority, String tag, @NotNull String message, Throwable t)来更改输出方式。log方法里面会判断message长度是否超长了。如果超了则分开打印。getTag主要是做了两件事,一个是获取是否有设置的tag值,如果没有则创建一个tag值。这里巧妙用到了Throwable().getStackTrace()里面的StackTraceElement[] 来获取该调用的类的类名。如果是加了混淆可能是调用不出来,这点要注意了。最好设置debug开关,或者自己填写tag信息。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章