I find that this works well:
package com.paintedintel.util;
public class Log{
public static void out(final String output) {
System.out.println(output);
}
public static void debug(String output) {
System.err.println(Log.currentLocation() + " " + output);
}
public static String currentLocation() {
StackTraceElement classMethod = new Throwable()
.getStackTrace()[2];
String currMethod = classMethod.getMethodName();
String fullClass = classMethod.getClassName();
String[] smplClass = fullClass.split("\\.");
return smplClass[smplClass.length - 1] + "." + currMethod;
}
}
You can call it as
Log.debug("my message " + myParameters);
I have it printing out the simpleClassName() rather than the package class name which you can't get at directly which is the
split("\\."); //yes you need to escape the "."
Other than that, it can track where you're debug output is coming from automatically. Or you could just use it to get the method and class names.
If you combine the debug and currentLocation methods you'll have to use a lower index to get the line you want....
StackTraceElement classMethod = new Throwable()
.getStackTrace()[2]; // use a different index [x] w/exr methods
Method
object. i.e. Why do you need it?%L
or%M
options) but warn that it's very slow, because IIRC they're just callingThread.currentThread().getStackTrace()
as well.sun.reflect.Reflection.getCallerClass(int)
This can more efficient, but platform dependant and it doesn't give you the method.