I want to use timber in a separate module to handle logging in my android app, so that it can be called from any module and log to an internal file.
The problem is that the auto tagging doesn't work when used in a separate class instead of calling the timber log methods directly.
For example, I have a logging class with method in Logger.kt:
fun d(message: String)
{
Timber.d(message)
}
But when I call this from anywhere, it obviously uses the log class as the tag instead of the class calling the method.
So my question is, how could I pass the calling class automatically via this method? I do not want to add an additional variable like 'TAG = classname', since I might as well use normal logging in that case.
Is it possible to retrieve the method's calling class? or is there a better way to do central logging? The main purpose is to not have to define a TAG variable, while also being able to add file logging later.
You can use an extension function like:
This way the
logdmethod will be available anywhere and will not clash with the default log behavior.The
this.javaClass.simpleNamewill be used as the TAG, and will be logged with the actual caller class name.