Log method name and line number in Timber

That is how i solved it in my Application class using Kotlin:

class App : Application() {

override fun onCreate() {
    super.onCreate()
    initLogger()
}

private fun initLogger() {
    if (BuildConfig.DEBUG) {
        Timber.plant(object : Timber.DebugTree() {
            override fun createStackElementTag(element: StackTraceElement): String? {
                return "(${element.fileName}:${element.lineNumber})#${element.methodName}"
            }
        })
    }
}

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


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
        }
    }
}