It is not a duplication. The "object" expression is the keyword.
I am trying to integrate Timber Android Library with https://github.com/orhanobut/logger and I need a customLogStrategyForTimber for my needs.
I came up with this logic. But I am having difficulty on initializing the customLogStrategyForTimber
class App : Application() {
// I CREATED THE lateinit VARIABLE
lateinit var customLogStrategyForTimber: LogStrategy
override fun onCreate() {
super.onCreate()
Timber.plant(object : Timber.DebugTree() {
override fun log(
priorityTimber: Int, tagTimber: String?, message: String, t: Throwable?
) {
// USED THE lateinit HERE
customLogStrategyForTimber = object : LogcatLogStrategy() {
override fun log(priority: Int, tag: String?, message: String) {
super.log(priorityTimber, tagTimber, message)
}
}
println("customLogStrategyForTimber: ${::customLogStrategyForTimber.isInitialized}") // PRINTS TRUE
}
})
println("customLogStrategyForTimber OUTSIDE: ${::customLogStrategyForTimber.isInitialized}") // PRINTS FALSE - WHY??
var formatStrategy1 = PrettyFormatStrategy.newBuilder()
// TRYING TO CALL THE lateinit VARIABLE HERE
// NOW, HERE THE lateinit IS NOT INITIALIZED.
.logStrategy(customLogStrategyForTimber)
.build()
Logger.addLogAdapter(AndroidLogAdapter(formatStrategy1))
}
}
The customLogStrategyForTimber
is never initialized. Is there a better way to do this logic? Trying to add the entire formatStrategy
code inside the first override fun log method results in unexpected behaviour when using Timber logging, so that does not seem to be the easy option.
Crash when running the App
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property customLogStrategyForTimber has not been initialized
Tried using isInitialized
as well.
The code inside it never runs.
EDIT:
Created a sample project: https://github.com/shipsywor/demotimberlogger
EDIT 2:
I added println
statements to the code above. You will see that ::customLogStrategyForTimber.isInitialized
returns False at one point of code and True at another
NOTE: I cannot put formatStrategy code inside of Timber.plant {... }. It results in unexpected behavior.
Based on your comments on other answers, I think I understand what you're trying to do.
It looks like this would be less fragile code if you had a concrete implementation of LogcatLogStrategy where you have properties you can set.
Then you can have a single instance and can update it safely from anywhere.
What I don't know is if this updates your tag value on the correct thread or in the correct order for the tag to show up in your log correctly.
It would probably be easier to eliminate Timber entirely and just copy its method of determining the tag out of its source code into your LogcatLogStrategy, but I'm not familiar with this other logging library you're using. Maybe something like this: