Scala Play 2.1:在过滤器中访问请求和响应主体 [英] Scala Play 2.1: Accessing request and response bodies in a filter

查看:86
本文介绍了Scala Play 2.1:在过滤器中访问请求和响应主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我还需要记录请求和响应正文.这些都埋在Iterators/Enumerators中,是否有一种更简单的方法来访问主体而不必深入了解迭代的工作方式? 否则,如何将请求和响应主体转换为字符串?

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?

推荐答案

如果要捕获SimpleResult响应正文,请使用以下方法:

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
}

检查mimetype是否为json:

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

这篇关于Scala Play 2.1:在过滤器中访问请求和响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆