您的位置:首页 > 移动开发 > Android开发

android开发中怎么通过Log函数输出当前行号和当前函数名

2015-01-10 18:34 513 查看
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信息了
}
}


  

另一种使用形式:

public class DebugInfo extends Exception {
public int line() {
StackTraceElement[] trace = getStackTrace();
if (trace == null || trace.length == 0) {
return -1;
}
return trace[0].getLineNumber();
}

public String fun() {
StackTraceElement[] trace = getStackTrace();
if (trace == null || trace.length == 0) {
return "";
}
return trace[0].getMethodName();
}

public DebugInfo() {
super();
}

@Override
public String toString() {
return line() + "|" + fun() + "|";
}
}


使用方法

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


public class DebugInfo {
public static int line(StackTraceElement e) {
return e.getLineNumber();
}

public static String method(StackTraceElement e) {
return e.getMethodName();
}

public static String info(StackTraceElement e) {
String ret = line(e) + "|" + method(e) + "|";
return ret;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: