Reputation: 477
I am android developer and love logging very much. I had been using a convention for my logs that is in form of
[ClassName:methodName()]
Whenever i have to log something, this help me find exact location from where a specific log is generated and helpful in many cases.
Instead of writing each time the
ClassName
and
MethodName
manually i wrote a method. Their may be better approach of doing this. Any answer without using loop is Accepted.
public static String getRef(Object object) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
String method = "";
if (elements.length > 0) {
for (int i = 0; i < elements.length; i++) {
if (elements[i].getClassName().equals(object.getClass().getCanonicalName())) {
method = elements[i].getMethodName();
break;
}
}
}
return "[" + object.getClass().getSimpleName() + "::" + method + "()]";
}
Calling:
Log.d(STRING_TAG , GlobalConfig.getRef(this) + " Server Response:"+json);
i had already tried using
Object.getClass().getEnclosingMethod();
but its always returning me null and also it is supposed to return the method name where it is called right? as the documentation says
If this Class object represents a local or anonymous class within a method, returns a Method object representing the immediately enclosing method of the underlying class. Returns null otherwise. In particular, this method returns null if the underlying class is a local or anonymous class immediately enclosed by a type declaration, instance initializer or static initializer.
Return
Method the immediately enclosing method of the underlying class, if that class is a local or anonymous class; otherwise null.
Upvotes: 2
Views: 3074
Reputation: 3089
If you going to call it directly, I explain:
You can use this:
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
String method = "";
method = elements[elements.length - 2].getMethodName();
return "[" + object.getClass().getSimpleName() + "::" + method + "()]";
Where you get the last but one class called. Ex:
public class Random {
public static void main(String[] args) {
Random r = new Random();
r.test();
}
public void test() {
System.out.println(Logger.getRef(this));
}
}
class Logger {
public static String getRef(Object object) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
String method = "";
method = elements[2].getMethodName();
return "[" + object.getClass().getSimpleName() + "::" + method + "()]";
}
}
Out: [Random::test()]
Upvotes: 2