0

I know that stacktraces can be used to retrieve current executing method with something like this:

Thread.currentThread().getStackTrace()[what you want]

However not every JVM provides this stack trace so this way of getting a method's name is pretty much unreliable. Anyway...what about exceptions? My need is to log the caller method name and, in order to provide some code maintenance, I'd like to avoid to just write that name down like this:

public void myMethod(){
  ...

}catch(anException ex){
      log.error("myMethod failed!");
}

But rather something like:

}catch(anException ex){
      log.error("{} failed!", ex.getStackTrace()[0].getMethodName()); //0 should be my method, the caller
}

Is this reliable? I think that, at least for exceptions, JVM should be expected to provide said stack trace...

Phate
  • 6,066
  • 15
  • 73
  • 138
  • Have a look at this question, it is basically the same thing: http://stackoverflow.com/questions/421280/how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection. I was also thinking about Aspect oriented programming, but I do not believe it can be done that way. – hotzst Oct 10 '15 at 07:55
  • I'm afraid it's not..that's just the case in which the JVM implementation is not required to provide you the stack trace so that way is not reliable. My question is: what about inside exceptions?In this case I would expect to always have a stack trace so what I'm asking is if in this case my way of getting the caller is reliable. – Phate Oct 10 '15 at 08:05
  • Also, in my case, the caller's method name is in the FIRST element of the stack trace, not the last. – Phate Oct 10 '15 at 08:08
  • 1
    Every Java logging framework I have ever used in 18 years already logs the calling method name. What exactly is the question here? – user207421 Oct 10 '15 at 09:00
  • 1
    To go slightly off topic; why are you logging like that? Throwing away all of the stack trace but the final method is going to shoot you in the foot very quickly – Richard Tingle Oct 10 '15 at 09:19

1 Answers1

0

For anyone coming upon this post just now, I developed a maven plugin to address this issue:

PhilKes/slf4j-caller-info-maven-plugin

If you use SLF4J as your log and add the plugin as described in the README with the injection=%method you can simply write:

log.error("failed!");

and it will output:

[...] myMethod failed!
PhilKes
  • 78
  • 7