Jor*_*ito 0 java meta logging metaprogramming line-numbers
我想有一个方法来快速将详细信息转储到日志中.它会是这样的:
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).
}
Run Code Online (Sandbox Code Playgroud)
我已经知道了关于创建一个新的Exception对象并获取其堆栈跟踪的第一行的行号的技巧,但是通过使用它我必须添加行号作为参数,因为如果你在log方法中做了这个技巧,您将始终获得相同的行号(您进行操作的行之一).
有没有办法实现这一目标)?
您可以使用Exception的getStackTrace()方法来获取堆栈帧的列表.然后,您可以通过1个元素或使用某些逻辑向上移动堆栈(例如,直到获得不在您的日志记录类中的方法)并使用该StackTraceElement中的行号进行日志记录.
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |