Skip to content

Instantly share code, notes, and snippets.

@francisdb
Last active December 11, 2015 00:09
Show Gist options
  • Save francisdb/4514950 to your computer and use it in GitHub Desktop.
Save francisdb/4514950 to your computer and use it in GitHub Desktop.
Logging WS requests in playframework scala
// I'm looking for a better solution for the time logging (preferable in a transparent way)
private def logTime(message: String, promise: Future[Response]) = {
// not 100% ok, request is already running
// might even not be started yet
val now = System.currentTimeMillis
promise.onRedeem { response =>
val time = System.currentTimeMillis - now
logger.info(message + " => " + response.status + " " + time + "ms " + response.body.length + "b")
}
promise
}
def user(slug: String): Future[Option[User]] = {
val url = ...
logTime(url,
WS.url(url).get()
).map {
...handle response
}
}
@andypetrella
Copy link

A quick addition would be to have the promise value of logTime to be a call-by-name. This will clear the problem regarding the now value registering the start of the process. However, it's only true if the promise is created at that time... and not before

Secondly, keeping this like that, you could pimp the Promise returned by get() in order to add logTIme(). This way, the code will be simplest to read:

 WS.url(url).get().logTime(url).map(handler)

@francisdb
Copy link
Author

Now I also want to get rid of the url being used twice and the logging to contain the get/post/delete...

@andypetrella
Copy link

Being more fresh at the morning... I'm seeing my error! Pimping won't work because, it won't let you use the rest lazily (or by-name). So that's not a solution.

And, it'll be hard to get something quite integrated because we switch from a type to another in this call (from WSRequestHolder and Future) and since the get call is already creating the future for us it's even harder because we need to map it.

I thing the Play API is too restrictive at this point to allow a simpler solution :-/

@francisdb
Copy link
Author

I'll have to fork the play WS class then. Would have been nice if the async httpcliend had a global hook

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment