Tuesday, June 26, 2012

Logging Caller Method Info in Java

In our application, one method maybe called from multiple locations. While debugging application we may need to log it caller caller method information in those case following line will be use full.
Here from the current thread, I get called Stack and print that for us.


private static void someMethod() {
System.out.println(Thread.currentThread().getStackTrace()[0]);
System.out.println(Thread.currentThread().getStackTrace()[1]);
System.out.println(Thread.currentThread().getStackTrace()[2]);
}


java.lang.Thread.getStackTrace(Thread.java:1479)
demo.TestThread.someMethod(TestThread.java:14)
demo.TestThread.main(TestThread.java:9)

What we want from this output is "demo.TestThread.main(TestThread.java:9)" So you use in your java application.

System.out.println(Thread.currentThread().getStackTrace()[2]);  


Okey for Android Application I try followings:

public void onCreate(Bundle savedInstanceState) {
..................

        Log.i(TAG, "::onCreate:" +Thread.currentThread().getStackTrace()[0]);
        Log.i(TAG, "::onCreate:" +Thread.currentThread().getStackTrace()[1]);
        Log.i(TAG, "::onCreate:" +Thread.currentThread().getStackTrace()[2]);
        Log.i(TAG, "::onCreate:" +Thread.currentThread().getStackTrace()[3]);

............
}


onCreate:dalvik.system.VMStack.getThreadStackTrace(Native Method)
onCreate:java.lang.Thread.getStackTrace(Thread.java:591)
onCreate:demo.multi.line.text.DemoMultiLineTextActivity.onCreate(DemoMultiLineTextActivity.java:58)
onCreate:android.app.Activity.performCreate(Activity.java:4518)


What we want from this output is "onCreate:android.app.Activity.performCreate(Activity.java:4518)" So you use in your Android application:

        Log.i(TAG, "::onCreate:" +Thread.currentThread().getStackTrace()[3]);




No comments: