android開發中怎么通過Log函數輸出當前行號和當前函數名


public class Debug {
	public static int line(Exception e) {
		StackTraceElement[] trace = e.getStackTrace();
		if (trace == null || trace.length == 0)
			return -1; //
		return trace[0].getLineNumber();
	}
	public static String fun(Exception e) {
		StackTraceElement[] trace = e.getStackTrace();
		if (trace == null)
			return ""; //
		return trace[0].getMethodName();
	}
}

  使用場景:

public class test {
	public static String DI(Exception e) {
		return Debug.line(e)+"|"+Debug.fun(e)+"|";
	}
        public test() {
                 Log.d(TAG, DI(new Exception()));  //這里就輸出我們需要的debug信息了
        }
}   

  

 另一種使用形式:

 1 public class DebugInfo extends Exception {
 2     public int line() {
 3         StackTraceElement[] trace = getStackTrace();
 4         if (trace == null || trace.length == 0) {
 5             return -1;
 6         }
 7         return trace[0].getLineNumber();
 8     }
 9 
10     public String fun() {
11         StackTraceElement[] trace = getStackTrace();
12         if (trace == null || trace.length == 0) {
13             return "";
14         }
15         return trace[0].getMethodName();
16     }
17 
18     public DebugInfo() {
19         super();
20     }
21     
22     @Override
23     public String toString() {
24         return line() + "|" + fun() + "|";  
25     }
26 }

使用方法

Log.d(TAG, new DebugInfo() + "hello world!");

 

 1 public class DebugInfo {
 2     public static int line(StackTraceElement e) {
 3         return e.getLineNumber();
 4     }
 5 
 6     public static String method(StackTraceElement e) {
 7         return e.getMethodName();
 8     }
 9 
10     public static String info(StackTraceElement e) {
11         String ret = line(e) + "|" + method(e) + "|";
12         return ret;
13     }
14 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM