Log with link to source directly from Logcat

suggest change

This is a nice trick to add a link to code, so it will be easy to jump to the code that issued the log.

With the following code, this call

MyLogger.logWithLink("MyTag","param="+param);

results in:

07-26...012/com.myapp D/MyTag: MyFrag:onStart(param=3)  (MyFrag.java:2366) // << logcat converts this to a link to source!

This is the code (inside a class called MyLogger):

static StringBuilder sb0 = new StringBuilder(); // reusable string object

public static void logWithLink(String TAG, Object param) {
    StackTraceElement stack = Thread.currentThread().getStackTrace()[3];
    sb0.setLength(0);
    String c = stack.getFileName().substring(0, stack.getFileName().length() - 5); // removes the ".java"
    sb0.append(c).append(":");
    sb0.append(stack.getMethodName()).append('(');
    if (param != null) {
        sb0.append(param);
    }
    sb0.append(") ");
    sb0.append(" (").append(stack.getFileName()).append(':').append(stack.getLineNumber()).append(')');
    Log.d(TAG, sb0.toString());
}

This is a basic example. On Android, index 3 is normally the method that called logWithLink; index 4 is that method's caller. The exact indexes depend on the VM stack frames. The shared StringBuilder is not safe if logWithLink runs on more than one thread at once, and substring(..., length - 5) assumes the file name ends in .java.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents