简体   繁体   中英

Log only to a specific Timber Tree

I am using timber to log logs in my project. I have planted a DebugTree for my application in Application class. I am able to use timber to log my errors and exceptions.

I, also, have a library module to be used in this project. In the library module, I add Timber as a gradle dependancy same as my :app project. I want to be able to set a flag on library module to enable/disable its logging so that I can separate library logs from main :app project. Something like:

LibraryModule().setDeveloperMode(true)

As of now, all of my logs are being printed. If I plant a new tree in library, this will print logs two times for all library logs.

I have looked at this answer too: How to tell Timber which log call is for which Tree? But, this is not what I want, I don't want to reserve a logging priority for a library-module.

I wish I could do something like this, but unless the tree is planted, it won't print anything. right? But, if I plant it, logs will be repeated due to multiple trees.

val libraryTree: Timber.Tree = Timber.DebugTree()
libraryTree.d("library-logs")

How can I enable/disable Timber logs for my library?

Actually you don't need to handle planting inside the library itself. Just leaving it to app dev to add a version of the tree that he wants and you won't have duplicated logs.

Just log things you want to log and leave planting to users of the library.

If you want to handle it inside library, you can do:

class CustomLogTree(val printLogs: Boolean) : Timber.DebugTree() {

override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
    if (!printLogs) {
        return
    }
    super.log(priority, tag, message, t)
}

And expose function for changing "printLogs" flag for library consumers.

Also to prevent app planted logs to print library related information, call(logs will work inside app itself):

Timber.uprootAll()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM