經常調試Android framework錯誤,framework不可能想使用IDE來step-by-step的調試。
爲此,有時需要插入大量的log來幫助定位問題;有時知道了具體執行功能的函數,卻發現調用者太多仍難以定位問題,最後只得花大把時間去閱讀代碼。
作爲程序員,偷懶是種美德。我希望敲入調試語句的時候能偷懶一點,也希望能很容易地知道調用者是誰,於是有了下文。
package com.xxx.log; /** * The logger * * @author [email protected] * */ public class Lg { public static final void in() { print(Thread.currentThread().getStackTrace()[CUR_METHOD_INDEX] .getMethodName() + "() <---"); } public static final void out() { print(Thread.currentThread().getStackTrace()[CUR_METHOD_INDEX] .getMethodName() + "() --->"); } public static final void returnIn() { print(Thread.currentThread().getStackTrace()[CUR_METHOD_INDEX] .getMethodName() + "() --->, return"); } public static final void returnIn(String tag) { print(Thread.currentThread().getStackTrace()[CUR_METHOD_INDEX] .getMethodName() + "() --->, return" + (tag == null ? "" : " in " + tag)); } public static final void caseIn(String tag) { print(getMethodName() + "(), case" + (tag == null ? "" : " in " + tag)); } //just a example public static final void printStack() { Thread.dumpStack(); } // may use android.util.Log.i(); public static final void print(String info) { System.out.println(info); } public static final String getMethodName() { return Thread.currentThread().getStackTrace()[CUR_METHOD_INDEX] .getMethodName(); } // why = 2, see http://wenjuema.iteye.com/blog/643596 private static final int CUR_METHOD_INDEX = 2; }
//usage
public class TheMain {
/**
* @param args
*/
public static void main(String[] args) {
Lg.in();
mth2();
Lg.out();
}
static void mth1() {
Lg.in();
Lg.printStack();
Lg.out();
}
static void mth2() {
Lg.in();
System.out.println("do something");
mth1();
if (true) {
Lg.returnIn();
return;
}
Lg.out();
}
}
//output,當然,你的打印結果完全可能跟下邊不一樣,純屬正常。
main() <---
mth2() <---
do something
mth1() <---
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Thread.java:1249)
at com.xxx.log.Lg.printStack(Lg.java:37)
at TheMain.mth1(TheMain.java:16)
at TheMain.mth2(TheMain.java:23)
at TheMain.main(TheMain.java:10)
mth1() --->
mth2() --->, return
main() --->