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 {
fun frobnicate() {
Log.d(TAG, "Executing frobnicate")
}
fun fooBar() {
Log.d(TAG, "Executing fooBar")
}
companion object {
private val TAG: String = Frobnicator::class.simpleName!!
}
}
Setting a tag can be achieved in Timber by using the tag()
method, for instance:
Timber.tag(TAG).d("The medium is the massage")
Although please note that tag()
returns a new Tree
instance, hence the constant isn’t really needed and setting the tag can be shortened to returning the logger instance directly.
class DefaultFrobnicator : Frobnicator {
// no need to define the tag separately
private val log: Timber.Tree
get() = Timber.tag(Frobnicator::class.simpleName!!)
fun frobnicate() {
log.d("Executing frobnicate")
}
fun fooBar() {
log.d("Executing fooBar")
}
}