Reputation: 3895
Let's assume I would like to have an app with different loggers for each part of my logic, i.e, a ConsoleLogger for common messages and a HttpLogger for just remote communication.
I have seen that Timber allows you to create different loggers extending from Timber.Tree. Then, one could decide which logger to use relying on the the Android variant (DEBUG vs RELEASE) by modifying the onCreate method of your own Application's child class. In addition, it is possible to configure Timber to use one logger or the other by playing with the logging level (d, i, w, etc.).
Now, my question is, would it be possible to tell Timber on runtime which Tree to use? If it helps, I am trying to do something similar to how logback-android does with slf4j:
org.slf4j.Logger log = LoggerFactory.getLogger(MainActivity.class);
Upvotes: 1
Views: 1636
Reputation: 6839
I would suggest to handle it differently than constantly messing up with the Trees.
If you want HttpLogger
to log only http logs, you can create the logger in a way that it checks what is the tag for the message and log it only in case if the message contains the expected tag. Of course, you will need to manually put that tag in the place where you log the http message. But as the question is with #android tag, I guess you are using Retrofit, so you can log the requests in one place using an interceptor.
abstract class RemoteLoggerTree : Timber.Tree() {
companion object {
const val TAG_HTTP_LOG = "TAG_HTTP_LOG"
}
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (tag != TAG_HTTP_LOG) {
return
}
// log your stuff here as usual
}
}
Then on the call site you simply need to set a tag before logging, like this. It will be applied only to one log call.
Timber.tag(TAG_HTTP_LOG)
Timber.d("Your message goes here and will be logged in the HTTP logger")
If you don't want to have the duplicated logs by two loggers, you can do the opposite for the loggers that don't need to log these tagged messages.
Upvotes: 1
Reputation: 11
check out Timber.forest()
, this returns a collection of all planted trees.
Upvotes: 0
Reputation: 8941
You can have any number of loggers running at the same time. So different implementations could do different things in the d, i, v
logs. If you really need to stop one logger from running during runtime you can use the uproot(Tree tree)
or uprootAll()
methods to remove logging trees. And if you hadn't added your new one yet you'd use plant(Tree... trees)
.
Upvotes: 1