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信息。

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