I am trying to log the elapsed time of each task as follows.
The problem I have encountered is that the callback method within the logElapsedTime never gets called for some reason.
Only the very last callback to Future f is called.
How can I fix this so that each elapsed time is correctly logged?
def logElapsedTime[T](f: Future[T], description: String): Future[T] = {
val start = System.currentTimeMillis()
f onComplete (_ => logger.debug(s"$description took [${System.currentTimeMillis() - start}]"))
f
}
val f = for {
_ <- logElapsedTime(task1(), "1st task to be executed")
result <- logElapsedTime(task2(), "2nd task to be executed")
_ <- logElapsedTime(task3(), "3rd task to be executed")
_ <- logElapsedTime(task4(), "4th task to be executed")
} yield result
f onComplete {
case Success(v) =>
logger.info(s"tasks succeeded !!!! $v")
case Failure(ex) =>
logger.error(ex.getMessage)
throw ex
}
Output Samples ↓
when succeeded:
tasks succeeded !!!! some value
when failed:
some error message
No other inputs are logged.
(Log level is set to debug and above)