我希望有一种方法可以快速将详细信息转储到日志中。它会是这样的:
public static void log(String message, Class<?> sourceClass){
dump(formattedTime+sourceClass.getName()+"line"+lineNumberfromwhichthemessagecomes
(if several occurences are found, show all of them if there's no other way to
detectwhere has the method been called from).
}
我已经知道创建一个新的 Exception 对象并获取其堆栈跟踪第一行的行号的技巧,但是通过使用它,我必须添加行号作为参数,因为如果您在里面执行该技巧使用 log 方法,您将始终获得相同的行号(您进行操作的行号)。
有什么办法可以实现这一点吗?
最佳答案
您可以使用Exception的getStackTrace()方法来获取堆栈帧的列表。然后,您可以将堆栈向上移动 1 个元素或使用某种逻辑(例如,直到您获得一个不在日志记录类中的方法),并使用该 StackTraceElement 中的行号进行日志记录。
关于java - 检测参数字符串的代码行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12544603/