Timber簡介

剛剛接觸安卓的人事秀,一定對(duì)Log系列不陌生捉撮。我也同樣如此怕品。只是在一段時(shí)間后才知道,正式產(chǎn)品里面我們是不希望打印Log的巾遭,一是可能泄露不必要的信息肉康,二是對(duì)性能有那么一點(diǎn)影響,三是顯得不專業(yè)灼舍。
好在大神們?cè)缇投床炝诉@個(gè)問題吼和,然后各種庫應(yīng)運(yùn)而生。其中Timber是比較常見的庫片仿。
Timber的好處纹安,我個(gè)人認(rèn)為就是高度自定義化,你可以很方便地讓Timber按照你的需求來打印東西(以及做一些想做的事情)砂豌。其次其API延續(xù)了經(jīng)典的Log系列厢岂,幾乎沒有學(xué)習(xí)成本,上手很快阳距。
好了塔粒,吹了這么多看看怎么用吧~

添加依賴(版本以最新版本為準(zhǔn))

implementation 'com.jakewharton.timber:timber:4.7.0'

初始化

在app的Application子類onCreate()里面進(jìn)行初始化:

public class MyApp extends Application {

  @Override
  public void onCreate() {
    super.onCreate();
    if (BuildConfig.DEBUG) {
      // default logging
      Timber.plant(new Timber.DebugTree());
    }
    // blabla...
  }
}

上面這段是Timber最簡單的初始化方式,效果就是只在Debug版本的時(shí)候Timber會(huì)執(zhí)行打印筐摘。
那么Timber.plant(new Timber.DebugTree());是什么意思卒茬?
Timber這個(gè)英文單詞是木材的意思,Log也有伐木的意思咖熟,所以J神這么設(shè)計(jì)的意思就是圃酵,你種什么樹,得到什么木頭(種瓜得瓜馍管?)……好了我編不下去了郭赐。
事實(shí)上Tree在這里可以認(rèn)為是一套Log邏輯體系,而Timber支持多套體系共存确沸,也就是Forest(意思是森林捌锭,不過并不是一個(gè)類而是List<Tree>)。用法就是plant(Tree... trees)罗捎,效果就是每一棵Tree都會(huì)嘗試Log观谦,一般來說是用不到的。

Tree的簡介

所以說關(guān)鍵邏輯還是在Tree里面桨菜』碜矗看看Tree的源碼:

  /** 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);
    }
    // 省略類似的函數(shù)
   
    /** 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} 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);
  }

基本上囊括了Log的所有要素捉偏,包括優(yōu)先度,標(biāo)簽替蔬,字符信息告私,Throwable等。

然后看看自帶的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);
    }

    @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自定義了長度限制,假如標(biāo)簽缺省可以自動(dòng)從stackTrace中讀取標(biāo)簽等等根悼。

典型應(yīng)用

最典型的應(yīng)用就是用Timber來上報(bào)崩潰或者異常信息了凶异,在Debug模式下打印,在正式產(chǎn)品中不打印挤巡,而是把捕捉的異常發(fā)送出去剩彬。
Timber庫本身也帶了這么一個(gè)Sample:

public class ExampleApp extends Application {
  @Override public void onCreate() {
    super.onCreate();

    if (BuildConfig.DEBUG) {
      Timber.plant(new DebugTree());
    } else {
      Timber.plant(new CrashReportingTree());
    }
  }

  /** A tree which logs important information for crash reporting. */
  private static class CrashReportingTree extends Timber.Tree {
    @Override protected void log(int priority, String tag, @NonNull String message, Throwable t) {
      if (priority == Log.VERBOSE || priority == Log.DEBUG) {
        return;
      }

      FakeCrashLibrary.log(priority, tag, message);

      if (t != null) {
        if (priority == Log.ERROR) {
          FakeCrashLibrary.logError(t);
        } else if (priority == Log.WARN) {
          FakeCrashLibrary.logWarning(t);
        }
      }
    }
  }
}

要做的其實(shí)很簡單,首先就是拒絕VERBOSE和DEBUG級(jí)別的Log矿卑,然后把ERROR和WARN級(jí)別的東西上報(bào)即可喉恋。很小的東西,但是很方便母廷。從此不用再特意調(diào)用FakeCrashLibrary.logError(t);等代碼了轻黑。

總結(jié)

經(jīng)典庫,值得了解并嘗試一下琴昆。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末氓鄙,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子业舍,更是在濱河造成了極大的恐慌抖拦,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,607評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件舷暮,死亡現(xiàn)場(chǎng)離奇詭異态罪,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)下面,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門复颈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人诸狭,你說我怎么就攤上這事券膀。” “怎么了驯遇?”我有些...
    開封第一講書人閱讀 164,960評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵芹彬,是天一觀的道長。 經(jīng)常有香客問我叉庐,道長舒帮,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,750評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮玩郊,結(jié)果婚禮上肢执,老公的妹妹穿的比我還像新娘。我一直安慰自己译红,他們只是感情好预茄,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,764評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著侦厚,像睡著了一般耻陕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上刨沦,一...
    開封第一講書人閱讀 51,604評(píng)論 1 305
  • 那天诗宣,我揣著相機(jī)與錄音,去河邊找鬼想诅。 笑死召庞,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的来破。 我是一名探鬼主播篮灼,決...
    沈念sama閱讀 40,347評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼讳癌!你這毒婦竟也來了穿稳?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,253評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤晌坤,失蹤者是張志新(化名)和其女友劉穎逢艘,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體骤菠,經(jīng)...
    沈念sama閱讀 45,702評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡它改,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,893評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了商乎。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片央拖。...
    茶點(diǎn)故事閱讀 40,015評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖鹉戚,靈堂內(nèi)的尸體忽然破棺而出鲜戒,到底是詐尸還是另有隱情,我是刑警寧澤抹凳,帶...
    沈念sama閱讀 35,734評(píng)論 5 346
  • 正文 年R本政府宣布遏餐,位于F島的核電站,受9級(jí)特大地震影響赢底,放射性物質(zhì)發(fā)生泄漏失都。R本人自食惡果不足惜柏蘑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,352評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望粹庞。 院中可真熱鬧咳焚,春花似錦、人聲如沸庞溜。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽流码。三九已至督惰,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間旅掂,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評(píng)論 1 270
  • 我被黑心中介騙來泰國打工访娶, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留商虐,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,216評(píng)論 3 371
  • 正文 我出身青樓崖疤,卻偏偏與公主長得像秘车,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子劫哼,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,969評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 7.嗜賭如命男 我們村就有這樣的例子叮趴。 老鄭的老婆是村里的醫(yī)生,二十年前還是縣人大代表权烧。自己在村子里開了個(gè)廢品收購...
    劉秀玲閱讀 1,158評(píng)論 46 21
  • 有一份搭配眯亦,來源于細(xì)節(jié) 有一份執(zhí)著,來源于承諾 早安般码,就是一份簡簡單單的承諾 早餐妻率,就是一份純純正正的細(xì)節(jié) 陽光遇...
    溫如夏閱讀 280評(píng)論 3 5
  • 這盛世,愿如你所愿板祝。 盛世宫静,一個(gè)如此溫暖美好的詞。那輝煌券时,那榮光遍布的大地孤里,那種理所當(dāng)然的歸屬。盛世的花開橘洞,仿佛只...
    荼蘼花事閱讀 182評(píng)論 0 1