Cok*_*aka 6 logging scala enumerator playframework iterate
我正在寻找一种在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
}
}
Run Code Online (Sandbox Code Playgroud)
目前,已注释掉的代码无法正常工作,我的意思是,它会打印出来:
Response:
id=1
body=play.api.libs.iteratee.Enumerator$$anon$18@39e6c1a2
Run Code Online (Sandbox Code Playgroud)
所以,我需要找到一种从Enumerator [Array [Byte]]中获取String的方法.我试着通过阅读这篇文章来了解Enumerator的概念:http://mandubian.com/2012/08/27/understanding-play2-iteratees-for-normal-humans/
所以...,如果我理解正确的话:
我不应该在将它转换为String的过程中干掉枚举器.否则,客户端将不会收到任何信息.
让我们假设我弄清楚如何实现T /过滤器机制.但那么......它不会打败Play框架作为非阻塞流式传输框架的目的(因为我会在内存中构建完整的字节数组,然后在其上调用toString,最后记录它)?
那么,记录响应的正确方法是什么?
提前谢谢,拉卡
这段代码的工作原理:
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
我从这里学到了部分内容(关于如何从枚举器中获取字节数组):Scala Play 2.1:访问过滤器中的请求和响应主体。
我使用的是 Play 2.3.7,而我给出的链接使用的是 2.1(并且仍然使用 PlainResult,它在 2.3 中不再存在)。
归档时间: |
|
查看次数: |
1387 次 |
最近记录: |