经常调试Android framework错误,framework不可能想使用IDE来step-by-step的调试。
为此,有时需要插入大量的log来帮助定位问题;有时知道了具体执行功能的函数,却发现调用者太多仍难以定位问题,最后只得花大把时间去阅读代码。
作为程序员,偷懒是种美德。我希望敲入调试语句的时候能偷懒一点,也希望能很容易地知道调用者是谁,于是有了下文。
package com.xxx.log; /** * The logger * * @author wycfgq@21cn.com * */ 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
//output,当然,你的打印结果完全可能跟下边不一样,纯属正常。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(); } }
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() --->
注:好像有很多开源的日志工具,功能绝对强大,有空自己去研究一下。