playframework - Scala play http filters: how to find the request body -
i'm trying write filter similar simple 1 described in http://www.playframework.com/documentation/2.1.1/scalahttpfilters need access request body. documentation below states "when invoke next, iteratee. wrap in enumeratee transformations if wished." i'm trying figure out how wrap iteratee can request body string within filter can log well.
i spent time on this. no means scala expert works pretty well! :)
object accesslog extends essentialfilter { def apply(nextfilter: essentialaction) = new essentialaction { def apply(requestheader: requestheader) = { val starttime = system.currenttimemillis nextfilter(requestheader).map { result => val endtime = system.currenttimemillis val requesttime = endtime - starttime val bytestostring: enumeratee[ array[byte], string ] = enumeratee.map[array[byte]]{ bytes => new string(bytes) } val consume: iteratee[string,string] = iteratee.consume[string]() val resultbody : future[string] = result.body |>>> bytestostring &>> consume resultbody.map { body => logger.info(s"${requestheader.method} ${requestheader.uri}" + s" took ${requesttime}ms , returned ${result.header.status}") val jsonbody = json.parse(body) logger.debug(s"response\nheader:\n${result.header.headers.tostring}\nbody:\n${json.prettyprint(jsonbody)}") } result.withheaders("request-time" -> requesttime.tostring) } } }
the end result print body json string (pretty printed).
Comments
Post a Comment