Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Play 2.1: Accessing request and response bodies in a filter

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?

like image 375
user228726 Avatar asked Oct 04 '22 12:10

user228726


1 Answers

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
  }
}
like image 124
JMParsons Avatar answered Oct 07 '22 18:10

JMParsons