我正在寻找一种在 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。我试图通过阅读以下内容来掌握 Enumerator 的概念:http://mandubian.com/2012/08/27/understanding-play2-iteratees-for-normal-humans/
所以......,如果我理解正确的话:
那么,记录响应的正确方法是什么?
提前致谢,
拉卡
最佳答案
此代码有效:
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 中不再存在)。
关于scala - Play /记录/打印响应正文/遍历枚举器/缓冲正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27612300/