Android Logging on Steroids: Clickable Logs With Location Info

Merthan Erdem
ProAndroidDev
Published in
2 min readApr 26, 2020

--

Photo by Antonio Grosz on unsplash

Today I’ll quickly tell you a way to make every log in your application look like this with a clickable hyperlink to the location, just like with Exceptions:

D/(AddPictureFragment.kt:222)getImageCaptureId(): 3450803 

This was simply logged in the method getImageCaptureId() at line 222 of AddPictureFragment, and the call simply looked like this, no need to specify anything:

Timber.d("$id")

This often even takes away the need to define anything extra as even a “magic number” in the logs now gets lots of infos additionally added, worst case scenario when only specifying id would be that you have to click on the Class/Linenumber and see what was logged. Still miles better than the logging stuff I used before.

Additional Usages/Extensions

Not just that, but you can create methods like:

That allow you to just call .log() on any object and automatically gives you a useable log, to take the example from above with a variable named id you can just get a log like:

D/(AddPictureFragment.kt:222)getImageCaptureId(): 3450803

by doing

id.log()

Setup

First off, you’ll have to import the Timber library, so put this (check the current version first) into your app’s build.gradle

implementation 'com.jakewharton.timber:timber:4.7.1'

The only thing you need to do to setup Timber logging in general is “Planting” a Tree in your application class.

Instead of the default DebugTree we’ll use a class that extends from it and overrides createStackElementTag, which tells the Logger what the Tag (first part) of the Log should look like, which is also why we don’t need a variable for the actual log message.

After that the only thing we need to do is follow Timber’s setup guide, so call

Timber.plant(HyperlinkedDebugTree())

inside onCreate in your Application class and you are done.

You don’t even need to create a named class, you can also just use Kotlin’s anonymous class syntax and put the code into the Timber.plant call directly.

I created a Pull Request a while ago on the Timber library for this, as I think it makes sense to include something like this in the library itself (and if it’s included it should be mentioned in the Readme).

The PR also has a different Tree that let’s you pass whether or not you want to log the methodName, but that isn’t required as you can just customize your own HyperlinkedDebugTree here, feel free to choose a shorter name too :D.

Logging with Timber doesn’t happen in production applications so stuff like line-numbers/classes being logged won’t be a problem at all.

Thank you for reading, tell me if I can improve anything either in my Medium post or in the linked code. Have a great day!

--

--