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:


Will result 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];
    String c = stack.getFileName().substring(0, stack.getFileName().length() - 5); // removes the ".java"
    if (param != null) {
    sb0.append(") ");
    sb0.append(" (").append(stack.getFileName()).append(':').append(stack.getLineNumber()).append(')');
    Log.d(TAG, sb0.toString());

This is a basic example, it can be easily extended to issue a link to the caller (hint: the stack will be [4] instead of [3]), and you can also add other relevant information.

Feedback about page:

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

Table Of Contents