Scala Play 2.1: Accessing request and response bod

2019-05-07 00:22发布

I'm writing a filter to log all requests and their responses

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

I need to also log the request and response bodies. These are buried inside Iterators/Enumerators, is there an easier way to access the bodies without having to go into details of how iteratees work? Otherwise how can I convert the request and response bodies as a string?

2条回答
别忘想泡老子
2楼-- · 2019-05-07 00:46

No, there is no easier way. But you can take a look on my Google HTML Compressor filter.

查看更多
虎瘦雄心在
3楼-- · 2019-05-07 01:02

If you want to capture the SimpleResult response body use this:

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
}

Check mimetype for json:

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
  }
}
查看更多
登录 后发表回答