不能使用IDE调试? 照样能很快定位问题

19 篇文章 0 订阅
12 篇文章 0 订阅

        经常调试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

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() --->


注:好像有很多开源的日志工具,功能绝对强大,有空自己去研究一下。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值