5

我正在编写一个过滤器来记录所有请求及其响应

    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)
      }
    }
  }
}

我还需要记录请求和响应正文。这些隐藏在迭代器/枚举器中,是否有一种更简单的方法可以访问主体而无需详细了解迭代器的工作原理?否则如何将请求和响应正文转换为字符串?

4

2 回答 2

4

如果要捕获 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
}

检查 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
  }
}
于 2013-07-22T08:00:24.550 回答
0

不,没有更简单的方法。但是你可以看看我的Google HTML Compressor过滤器。

于 2013-07-20T10:55:47.583 回答