1

I'm setting up extension function for Timber. I want to have kind of function to send log to my server.

The problem for me is Dagger. I have instance of RestService class in dagger and I'm using it in my whole app. But to use it I need inject somewhere this RestService. I can't do it in constructor because I haven't it.

I want to have something like this:

fun Timber.serverLogDebug(log: String) {
    restService.log(log)
}

Is it probably at all? It will be convenience for me to use my mechanism like simple Timber.d(). Alternatively I can call

restService.log(log)

in every place. But I have to have this instance everywhere.

AdamN
  • 476
  • 5
  • 13
  • You can take your `restService` object at **Application class** and use for your extensions from there statically. – Jeel Vankhede Jan 08 '19 at 11:50
  • u can send your restService also as an argument for `fun Timber.serverLogDebug(log: String,restService:RestService)` – Anmol Jan 08 '19 at 12:12

1 Answers1

0

In the file where you define the extension function, also define a "singleton" object to hold your restService instance, create a setter for it, and reference it from the logger function.

private object ServiceHolder {
    var restService: RestService
}

fun Timber.setRestService(restService: RestService) {
    ServiceHolder.restService = restService
}

fun Timber.serverLogDebug(log: String) {
    ServiceHolder.restService.log(log)
}

Now you can "statically inject" your service instance by calling Timber.setRestService where you plant your Timber DebugTree.

Note: If you want to log to the server every time you log (or every time you log an event of a specific level), you might be better off creating a custom Timber.Tree.

Janos Breuer
  • 480
  • 2
  • 6