scala – 播放/记录/打印响应正文/运行枚举器/缓冲正文
我正在寻找一种在Play框架中打印响应体的方法,我有这样的代码:
object AccessLoggingAction extends ActionBuilder[Request] { def invokeBlock[A](request: Request[A],block: (Request[A]) => Future[Result]) = { Logger.info(s"""Request: id=${request.id} method=${request.method} uri=${request.uri} remote-address=${request.remoteAddress} body=${request.body} """) val ret = block(request) /* ret.map {result => Logger.info(s"""Response: id=${request.id} body=${result.body} """) } */ //TODO: find out how to print result.body (be careful not to consume the enumerator) ret } } 目前,已注释掉的代码无法正常工作,我的意思是,它会打印出来: Response: id=1 body=play.api.libs.iteratee.Enumerator$$anon$18@39e6c1a2 所以,我需要找到一种从Enumerator [Array [Byte]]中获取String的方法.我试着通过阅读这个:http://mandubian.com/2012/08/27/understanding-play2-iteratees-for-normal-humans/来掌握Enumerator的概念 所以…,如果我理解正确的话: >在将枚举器转换为String的过程中,我不应该干掉它.否则,客户端将不会收到任何信息. 那么,记录响应的正确方法是什么? 提前致谢, 解决方法
此代码有效:
object AccessLoggingAction extends ActionBuilder[Request] { def invokeBlock[A](request: Request[A],block: (Request[A]) => Future[Result]) = { val start = System.currentTimeMillis Logger.info(s"""Request: id=${request.id} method=${request.method} uri=${request.uri} remote-address=${request.remoteAddress} body=${request.body} """) val resultFut = block(request) resultFut.map {result => val time = System.currentTimeMillis - start Result(result.header,result.body &> Enumeratee.map(arrOfBytes => { val body = new String(arrOfBytes.map(_.toChar)) Logger.info(s"""Response: id=${request.id} method=${request.method} uri=${request.uri} delay=${time}ms status=${result.header.status} body=${body}""") arrOfBytes }),result.connection) } } } 我从这里部分学习了它(关于如何从枚举器中获取字节数组):Scala Play 2.1: Accessing request and response bodies in a filter. 我正在使用Play 2.3.7,而我给出的链接使用2.1(并且仍使用PlainResult,2.3中不再存在). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |