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]);




1 comment:

mary Brown said...

Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.