剛剛接觸安卓的人事秀,一定對(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)典庫,值得了解并嘗試一下琴昆。