In a logging system, every log output is done by a helper class with a method such as this one
public void debug(String message) {
Logger logger = Logger.getLogger(getCallingClass());
logger.debug(message);
}
...
public Class getCallingClass() {
/*
Calls Thread.getStackTrace() and back traces until the class on the stack trace
!= this.getClass().
*/
return classFound;
}
How expensive is this to run and could it have significant performance hits?
Now with JDK 9 & 10, you can use StackWalker, which is not an expensive call.
private void invoke006() {
var stack = StackWalker.getInstance(StackWalker.Option.SHOW_HIDDEN_FRAMES).walk((s) -> s.collect(Collectors.toList()));
stack.forEach(stackFrame -> {
if (stackFrame.getMethodName().equals("masterInvoker")) {
System.err.println("master called !!");
System.err.println(StackWalker.getInstance().walk((s) -> s.collect(Collectors.toList())).get(0).getMethodName() + ", line: " + StackWalker.getInstance().walk((s) -> s.collect(Collectors.toList())).get(0).getLineNumber());
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With