use*_*726 5 scala playframework playframework-2.0
我正在编写一个过滤器来记录所有请求及其响应
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)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我还需要记录请求和响应主体。它们埋藏在迭代器/枚举器中,是否有一种更简单的方法来访问它们的主体,而不必详细了解迭代器如何工作的细节?否则如何将请求和响应正文转换为字符串?
如果您想捕获 SimpleResult 响应正文,请使用以下命令:
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
}
Run Code Online (Sandbox Code Playgroud)
检查 json 的 mimetype:
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1831 次 |
| 最近记录: |