Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log method name and line number in Timber

Is possible log the current line number and method name using the Timber library?

Expected LogCat result:

ismaeldivita.myapp I/[L:22] [M:onResume] [C:HomeActivity]: Praise the log!
like image 321
Ismael Di Vita Avatar asked Jul 31 '16 23:07

Ismael Di Vita


People also ask

Why timber is used in Android?

Benefits of using Timber vs Android Logging No need to worry about TAGS: Timber generates the TAGs automatically for you so you don't have to worry about including a global TAG in every class. No need to manually remove Log statements: As already shown, it's really easy to disable Logging for release apps.


2 Answers

Answering my own question.

Just create a new DebugTree class

public class MyDebugTree extends Timber.DebugTree {    
    @Override
    protected String createStackElementTag(StackTraceElement element) {
        return String.format("[L:%s] [M:%s] [C:%s]",
                element.getLineNumber(),
                element.getMethodName(),
                super.createStackElementTag(element));
    }
}

And plant your Tree in Timber:

public class App extends Application {
    @Override
    public void onCreate(){
        super.onCreate();
        if (BuildConfig.DEBUG) {
           Timber.plant(new MyDebugTree());
        } else {
           //TODO plant your Production Tree
        }
    }
}
like image 121
Ismael Di Vita Avatar answered Sep 28 '22 01:09

Ismael Di Vita


improving on Ismael Di Vita answer so it displays in logcat as a hyperlink like this.

public class MyDebugTree extends Timber.DebugTree {     
    @Override 
    protected String createStackElementTag(StackTraceElement element) {
        return String.format("(%s:%s)#%s",
            element.getFileName(),
            element.getLineNumber(),
            element.getMethodName());
    } 
} 

or for kotlin

class LineNumberDebugTree : Timber.DebugTree() {
override fun createStackElementTag(element: StackTraceElement): String? {
    return "(${element.fileName}:${element.lineNumber})#${element.methodName}"
}

}

Note: use element.fileName instead of element.className so it works in kotlin for logging outside a class

from my utils lib

like image 41
humazed Avatar answered Sep 28 '22 01:09

humazed