Another sample for android usage:
//package your.package.name;
import android.util.Log;
/*
File name: MyDebugLog.java
*/
public class MyDebugLog {
private static final int index = 4; // <== Index in call stack array
private static final String methodName = "Log"; // <== Name of method for public call
private static String getCallerName() {
String caller = "NONE";
final StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
for (int i = 0; i < stacktrace.length; i++) {
Log.e("Method ", "[" + i + "]" + stacktrace[i].getMethodName());
}
if (stacktrace.length >= index){
caller = stacktrace[index].getMethodName();
}
return caller;
}
private static String getTag() {
String tag = "NONE";
final StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
for (int i = 0; i < stacktrace.length; i++) {
Log.e("Method ", "[" + i + "]" + stacktrace[i].getMethodName());
if (stacktrace[i].getMethodName().equals(methodName)) {
tag = "("+stacktrace[i + 1].getFileName() + ":" + stacktrace[i + 1].getLineNumber()+")";
return tag;
}
}
return tag;
}
public static void Log(String message){
Log.v(getTag(), getCallerName() + " " + message);
}
}
Usage:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_main);
MyDebugLog.Log("XXXXX");
}
Output:
V/(MainActivity.java:117): onCreate XXXXX
Sample of arrays:
getTag Sample of stacktace array:
Method: [0]getThreadStackTrace
Method: [1]getStackTrace
Method: [2]getTag
Method: [3]Log <== Method for external call
...
getName Sample of stacktace array:
Method: [0]getThreadStackTrace
Method: [1]getStackTrace
Method: [2]getCallerName
Method: [3]Log
Method: [4]onCreate <== Our external method
Method: [5]performCreate
...