I've got a J2EE web application that I'm working on and when an exception occurs, I'd like to get some basic details about the exception and log it. The message that I'm logging should be pretty basic, something that might mean something to the people running the web server(s).
Would using e.getMessage() be the best thing to log? Thanks.
Possibly. Problem is that without at least the calling method info, this isn't terribly helpful
Consider something like the following
/**
* Returns <i>class.method:linenumber</i> of the caller (or, more accurately
* the caller of the caller).
* </p>
*
* <p>
* Returns unknown if stacktrace is mucked up. Uses reflection and string
* concatenation, so don't overuse this for trivial matters. For exception
* handling and for logging, on the other hand, it is useful.
*
* @return method name of caller's caller and line number (String)
*/
public static String returnCaller( Class ignoreMe )
{
String ignoreClass = ignoreMe.getName();
StackTraceElement[] steArr = new Throwable().getStackTrace();
if (steArr != null)
{
// subscript 1 is returnCaller().
// subscript 2 is the caller of returnCaller()
// subscript 3 is the caller of the caller of returnCaller()...
for( int i = 0; i < steArr.length; i++)
{
if (steArr[i] == null)
break;
String myclass = steArr[i].getClassName();
if (myclass.equals(ErrorHandle.class.getName()))
continue;
if (ignoreClass.equals(myclass))
continue;
return steArr[i].getClassName()
+ "."
+ steArr[i].getMethodName()
+ ":"
+ steArr[i].getLineNumber();
}
}
return "unknown";
}
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