刚刚接触安卓的人,一定对Log系列不陌生。我也同样如此。只是在一段时间后才知道,正式产品里面我们是不希望打印Log的,一是可能泄露不必要的信息,二是对性能有那么一点影响,三是显得不专业。
好在大神们早就洞察了这个问题,然后各种库应运而生。其中Timber是比较常见的库。
Timber的好处,我个人认为就是高度自定义化,你可以很方便地让Timber按照你的需求来打印东西(以及做一些想做的事情)。其次其API延续了经典的Log系列,几乎没有学习成本,上手很快。
好了,吹了这么多看看怎么用吧~
添加依赖(版本以最新版本为准)
implementation 'com.jakewharton.timber:timber:4.7.0'
初始化
在app的Application子类onCreate()
里面进行初始化:
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
// default logging
Timber.plant(new Timber.DebugTree());
}
// blabla...
}
}
上面这段是Timber最简单的初始化方式,效果就是只在Debug版本的时候Timber会执行打印。
那么Timber.plant(new Timber.DebugTree());
是什么意思?
Timber这个英文单词是木材的意思,Log也有伐木的意思,所以J神这么设计的意思就是,你种什么树,得到什么木头(种瓜得瓜?)……好了我编不下去了。
事实上Tree
在这里可以认为是一套Log逻辑体系,而Timber支持多套体系共存,也就是Forest(意思是森林,不过并不是一个类而是List<Tree>)。用法就是plant(Tree... trees)
,效果就是每一棵Tree都会尝试Log,一般来说是用不到的。
Tree的简介
所以说关键逻辑还是在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);
}
// 省略类似的函数
/** 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的所有要素,包括优先度,标签,字符信息,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自定义了长度限制,假如标签缺省可以自动从stackTrace
中读取标签等等。
典型应用
最典型的应用就是用Timber来上报崩溃或者异常信息了,在Debug模式下打印,在正式产品中不打印,而是把捕捉的异常发送出去。
Timber库本身也带了这么一个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);
}
}
}
}
}
要做的其实很简单,首先就是拒绝VERBOSE和DEBUG级别的Log,然后把ERROR和WARN级别的东西上报即可。很小的东西,但是很方便。从此不用再特意调用FakeCrashLibrary.logError(t);
等代码了。
总结
经典库,值得了解并尝试一下。