Search code examples
androidlogcat

android: How to create an hyperlink to a code line using Log.d


I am learning logging in android code using android studio and emulator

I found that the following command shows a traceback with hyperlink to the code location

Log.d("TAG", "Message with stack trace info", new Throwable());

the image of logcat with hyperlink is

enter image description here

How can I create only the hyperlink part in my log message, without any traceback output


Solution

  • Try this, for example:

    import android.util.Log;
    
    public class Logger {
    
        public static void log(String tag, String message) {
            String caller = getCallerInfo(new Throwable().getStackTrace());
            Log.d(tag, message + caller);
        }
    
        private static String getCallerInfo(StackTraceElement[] stacks) {
            if (stacks == null || stacks.length < 1) {
                return "";
            }
            StackTraceElement stack = stacks[1];
            return String.format(" (%s:%s)", stack.getFileName(), stack.getLineNumber());
        }
    }
    

    And call it from any where in your code

    Logger.log("Manowar", "Today is the good day to die");