问题

如何将行号打印到日志中。假设在向日志输出一些信息时,我还想打印输出在源代码中的行号。正如我们在堆栈跟踪中看到的,它显示发生异常的行号。异常对象上可以使用堆栈跟踪。

其他替代方案可以是在打印到日志时手动包括行号。还有别的办法吗?


#1 热门回答(83 赞)

FromAngsuman Chakraborty

/**Get the current line number.
 * @return int - Current line number.
 */
public static int getLineNumber() {
    return Thread.currentThread().getStackTrace()[2].getLineNumber();
}

#2 热门回答(67 赞)

我们最终在Android工作中使用了这样的自定义类:

import android.util.Log;    
public class DebugLog {
 public final static boolean DEBUG = true;    
 public static void log(String message) {
  if (DEBUG) {
    String fullClassName = Thread.currentThread().getStackTrace()[2].getClassName();
    String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
    String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
    int lineNumber = Thread.currentThread().getStackTrace()[2].getLineNumber();

    Log.d(className + "." + methodName + "():" + lineNumber, message);
  }
 }
}

#3 热门回答(28 赞)

快速而肮脏的方式:

System.out.println("I'm in line #" + 
    new Exception().getStackTrace()[0].getLineNumber());

有一些更多细节:

StackTraceElement l = new Exception().getStackTrace()[0];
System.out.println(
    l.getClassName()+"/"+l.getMethodName()+":"+l.getLineNumber());

这将输出如下内容:

com.example.mytest.MyClass/myMethod:103

原文链接