Friday, September 10, 2010

Print Java class/method name, line number in your log file

Sometime it's very helpful to print verbose information in the log file, of course it will have impact on your performance.

Get class name is very easy, but dynamically get the method name and line number at the point you put your log message need you get help from Throwable class,

When we call new Throwable(), in the constructor, it first call fillInStackTrace() method, after the object is created, we could call throwable.getStackTrace() which returns an array of StackTraceElement, StackTraceElement[0] will be the method which creates the Throwable() object, StackTraceElement[1] will be the one outside the preivous mehtod, and so on. For exampe:

No comments:

Post a Comment