How to insert a log in LogCat that when I click on it jumps to its line in code?

前端 未结 7 1875
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 10:16

I want to insert a log in LogCat that when I click on it jumps to its line like some error logs that are generated by system.

Is it possible?

7条回答
  •  星月不相逢
    2020-12-15 10:50

    The important thing is to insert "(X:Y)" in your log message, while X is your desired file name and Y is your desired line number in X. (I learned it from @breceivemail's answer). So try:

    public static void log(final String tag, final String msg) {
        final StackTraceElement stackTrace = new Exception().getStackTrace()[1];
    
        String fileName = stackTrace.getFileName();
        if (fileName == null) fileName="";  // It is necessary if you want to use proguard obfuscation.
    
        final String info = stackTrace.getMethodName() + " (" + fileName + ":"
                + stackTrace.getLineNumber() + ")";
    
        Log.LEVEL(tag, info + ": " + msg);
    }
    

    Note: The LEVEL is the log level and can be v, d, i, w, e or wtf.

    Now you can use log(tag, msg) instead of Log.LEVEL(tag, msg).


    Example:

    MainActivity.java:

    ...
    public class MainActivity extends BaseActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            log("Test Tag", "Hello World!");
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ...
        ...
    

    The output:

    12-30 14:24:45.343 ? I/Test Tag: onCreate (MainActivity.java:10): Hello World!
    

    And MainActivity.java:10 automatically would be a link and you can click on it!


    You can also assign following value to info variable if you want more verbose log:

    final String info = stackTrace.getClassName() + "." + stackTrace.getMethodName() + " ("
                + fileName + ":" + stackTrace.getLineNumber() + ")\n";
    

    So the output of above example would be:

    12-30 14:33:07.360 ? I/Test Tag: com.example.myapp.MainActivity.onCreate (MainActivity.java:11)
                                     Hello World!    
    

提交回复
热议问题