Scala Playback 2.1: Access to request and response bodies in a filter

I am writing a filter to register all requests and their responses

object LoggingFilter extends EssentialFilter { def apply(next: EssentialAction) = new EssentialAction { def apply(rh: RequestHeader) = { val start = System.currentTimeMillis def logTime(result: PlainResult): Result = result match { case simple @ SimpleResult(header, content) => val time = System.currentTimeMillis - start play.Logger.info(s"${rh.method} ${rh.uri} took ${time}ms and returned ${header.status}") result case _ => result } next(rh).map { case plain: PlainResult => logTime(plain) case async: AsyncResult => async.transform(logTime) } } } } 

I also need to register the request and response bodies. They are buried inside iterators / counters, is there an easier way to gain access to bodies without going into details about how they work? Otherwise, how can I convert the request and response bodies as a string?

+4
source share
2 answers

If you want to capture the body of the SimpleResult response, use this:

 def logTime(result: PlainResult): Result = result match { case simple @ SimpleResult(header, content) => { val time = System.currentTimeMillis - start SimpleResult(header, content &> Enumeratee.map(a => { play.Logger.info(s"${rh.method} ${rh.uri} took ${time}ms and returned ${header.status} with body ${a}") simple.writeable.transform(a) })) } case _ => result } 

Check mimetype for json:

 def logTime(result: PlainResult): Result = { result.header.headers.get(HeaderNames.CONTENT_TYPE) match { case Some(ct) if ct.trim.startsWith(MimeTypes.JSON) => result match { case simple @ SimpleResult(header, content) => val time = System.currentTimeMillis - start SimpleResult(header, content &> Enumeratee.map(a => { play.Logger.info(s"${rh.method} ${rh.uri} took ${time}ms and returned ${header.status} with body ${a}") simple.writeable.transform(a) })) } case ct => result } } 
+3
source

No, there is no simpler way. But you can see my Google HTML Compressor filter.

0
source

Source: https://habr.com/ru/post/980081/


All Articles