The Android logging functions (the methods of the Log class) accept a tag argument that can be used to identify the source of the log message.
It is common practice to use a constant to define this tag, like in the following example:
class Frobnicator {
private val listener = object : FooBarListener {
override fun listen() {
Log.d(TAG, "Logging with expected tag")
}
}
fun frobnicate() {
Log.d(TAG, "Executing frobnicate")
}
companion object {
private val TAG: String = "Frobnicator"
}
}
Setting a tag can be achieved in Timber by using the tag() method, for instance:
Timber.tag(TAG).d("The medium is the massage")
Why set the tag explicitly?
Timber has auto-tagging and it works by retrieving the class name associated with the last element on the stack, i.e. the name of the last called class. The problem is that using the last called class as the tag sometimes can be uninformative or misleading, because it’s not always logging the last called class makes the most sense. For instance the logging call can be inside an anonymous class or extension function and hence setting the tag explcitly becomes useful.
With Timber the tag() function returns a new Tree
instance and, unlike the example above, having a constant isn’t really needed and setting the tag can be shortened to returning the logger instance directly:
class Frobnicator {
// no need to define the tag separately
private val log: Timber.Tree
get() = Timber.tag("Frobnicator")
private val listener = object : FooBarListener {
override fun listen() {
log.d("Logging with expected tag")
}
}
fun frobnicate() {
log.d("Executing frobnicate")
}
}