'Timber filter logs by tag

When using Timber, I can see tags being automatically generated, which is nice. However, I can't really access these tags in code. I can only see them in Logcat, but I don't know how to filter them.

I know it is possible to turn on logging for debug builds only:

if (BuildConfig.DEBUG) {
    Timber.plant(DebugTree())
}

However, this isn't very useful for me. I tried to do:

Timber.plant(Timber.tag("TroublesomeClass"))

But I am getting:

java.lang.IllegalArgumentException: Cannot plant Timber into itself.

.. which makes no sense at all to me.

Is there any way how to filter Timber logs by the tag?

Thank you in advance!



Solution 1:[1]

Finally, I figured this one out. It is actually really simple. You just need to subclass Timber.DebugTree like this:

/**
* Custom Timber logging tree allowing to filter logs by Tag.
*/
class FilteringTimberTree(val allowedTags: List<String> = ArrayList(),
                        var filteringEnabled: Boolean = true) : Timber.DebugTree() {

    override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
        if(!filteringEnabled || allowedTags.contains(tag)) {
            super.log(priority, tag, message, t)
        }
    }
}

And then plant the tree in Application class:

val allowedTags = arrayListOf("Tag1", "Tag2", "Tag3")
Timber.plant(FilteringTimberTree(allowedTags))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Firzen