我们如何在java中将行号打印到日志中
如何将行号打印到日志。比如说,在将一些信息输出到日志时,我还想在源代码中输出输出的行号。正如我们在堆栈跟踪中看到的那样,它显示发生异常的行号。堆栈跟踪在异常对象上可用。
其他替代方法可能是在打印到日志时手动包括行号。还有其他方法吗?
如何将行号打印到日志。比如说,在将一些信息输出到日志时,我还想在源代码中输出输出的行号。正如我们在堆栈跟踪中看到的那样,它显示发生异常的行号。堆栈跟踪在异常对象上可用。
其他替代方法可能是在打印到日志时手动包括行号。还有其他方法吗?
来自 Angsuman Chakraborty (存档) :
/** Get the current line number.
* @return int - Current line number.
*/
public static int getLineNumber() {
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
我们最终在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);
}
}
}