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 }
原文地址:https://www.cnblogs.com/superPerfect/p/4215400.html