Scala Play 2.1:访问过滤器中的请求和响应主体

时间:2013-07-19 17:31:00

标签: 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)
      }
    }
  }
}

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

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