Android Get Calling Method and Line Number

Android Get Calling Methods and Line Numbers

Android get calling method

Getting logcat to display the file, method, and line number of your log calls

Android Get Calling Method and Line Numbers. This is a quick and easy one. If you ever found yourself wondering where the Log.i call you are reading in logcat came from then this is the class for you. You can do this rather easily by implementing a custom logging method. In my case I use a Utils class to handle this process. For the sake of easy reading I am only including the methods from my Utils class relating to the concept of this snippet.

 

 Utils class

/*
 * Utils class with toggling log messages that return the calling
 * method, file name, and line number
 */
public class Utils {
	/*
	 * debug variable enables/disables all log messages to logcat
	 * Useful to disable prior to app store submission
	 */
	public static final boolean debug = true;

	/*
	 * l method used to log passed string and returns the
	 * calling file as the tag, method and line number prior
	 * to the string's message
	 */
	public static void l(String s) {
		if (debug) {
			String[] msg = trace(Thread.currentThread().getStackTrace(), 3);
			Log.i(msg[0], msg[1] + s);
		} else {
			return;
		}
	}

	/*
	 * l (tag, string)
	 * used to pass logging messages as normal but can be disabled
	 * when debug == false
	 */
	public static void l(String t, String s) {
		if (debug) {
			Log.i(t, s);
		} else {
			return;
		}
	}

	/*
	 * trace
	 * Gathers the calling file, method, and line from the stack
	 * returns a string array with element 0 as file name and 
	 * element 1 as method[line]
	 */
	public static String[] trace(final StackTraceElement e[], final int level) {
		if (e != null && e.length >= level) {
			final StackTraceElement s = e[level];
			if (s != null) { return new String[] {
					e[level].getFileName(), e[level].getMethodName() + "[" + e[level].getLineNumber() + "]"
			};}
		}
		return null;
	}
}

 

Usage:

You can use this method by replacing any Log.i(tag, string) calls with Utils.l(string).

 

Example of original Log.i call:

@Override
protected void onResume() {
	super.onResume();
	Log.i("inits", "init resume");
}

Which returns a logcat output of:

inits | init resume

 

Example of replacing Log.i call with the new Utils.l call:

@Override
protected void onResume() {
	super.onResume();
	Utils.l("init resume");
}

Your logcat output will now display as:

SourceListActivity.java | onResume[119] init resume

 

These methods provided in the Utils class can easily be replicated to cover all of the Log.? methods. This allows for much faster debugging when using Log methods.




Leave a Reply