Android之TimingLogger类
概述
摘自官方文档:
A utility class to help log timings splits throughout a method call. Typical usage is:TimingLogger timings = new TimingLogger(TAG, "methodA");
// ... do some work A ... timings.addSplit("work A");
// ... do some work B ... timings.addSplit("work B");
// ... do some work C ... timings.addSplit("work C");
timings.dumpToLog();
The dumpToLog call would add the following to the log:
D/TAG ( 3459): methodA: begin
D/TAG ( 3459): methodA: 9 ms, work A
D/TAG ( 3459): methodA: 1 ms, work B
D/TAG ( 3459): methodA: 6 ms, work C
D/TAG ( 3459): methodA: end, 16 ms
以下是针对TimingLogger的封装:
public class MethodTimeTraceLogger {
private String tag;
private TimingLogger logger;
public MethodTimeTraceLogger(String tag) {
this.tag = tag;
}
public MethodTimeTraceLogger setLoggerLabel(String label) {
if (logger != null) {
logger.reset(tag, label);
} else {
logger = new TimingLogger(tag, label);
}
return this;
}
public MethodTimeTraceLogger addSplit(String msg) {
logger.addSplit(msg);
return this;
}
public void dumpToLog() {
logger.dumpToLog();
}
}
调用方式如下,
常见错误
1.无法输出日志原因分析:在TimingLogger的构造方法中会依次调用reset(tag, label)->reset(tag, label)->reset()方法,其中有这样一条语句:mDisabled = !Log.isLoggable(mTag, Log.VERBOSE);这个mDisable的值表示mTag为VERBOSE级别时是否不能打印,如果用Log打印一下,会发现它的值为true,就是说不能打印级别为VERBOSE的mTag的日志。因为默认情况下只打印INFO以上的日志,所以可通过以下命令,使其在日志级别为VERBOSE以上时都可以打印:
adb shell setprop log.tag.[
TimingLogger实例化时的TAG值] VERBOSE改进版:自定义MethodDebugLogger测试类
/**
* Created by Administrator on 2016/6/3.
* 方法调试日志类
*/
public class MethodDebugLogger {
private static final UtilsLog lg = UtilsLogFactory.getLogger(MethodDebugLogger.class);
private long startTime;
private long wholeTime = 0;//花费总时间
private String methodName;
private StringBuilder stringBuilder;
public MethodDebugLogger(String methodName) {
this.startTime = getStandedTime();
this.methodName = methodName;
this.wholeTime = 0;
this.stringBuilder = new StringBuilder(this.methodName).append(":start");
}
public MethodDebugLogger addSplit(String msg) {
long curTime = getStandedTime();
this.stringBuilder.append("\n")
.append(methodName)
.append(":")
.append(curTime - startTime)
.append("ms,")
.append(msg);
this.wholeTime += (curTime - startTime);
this.startTime = curTime;
return this;
}
public void dumpToLog() {
this.stringBuilder.append("\n").append(methodName).append(":").append(wholeTime).append(",end with whole time");
lg.e(this.stringBuilder.toString());
}
/**
* 获得标准时间
*
* @return
*/
public long getStandedTime() {
return System.currentTimeMillis();
}
}