在akka-http中跟踪http请求的生命周期

时间:2016-07-16 18:46:18

标签: scala akka akka-http

我希望能够在日志文件中跟踪具有唯一ID的请求。我设法做到这一点的最好方法是这样,但这意味着对于每个请求,将实例化一个新的exceptionHandler,rejectionHandler,routes和logRequestTimeRoutes。不应该为每个请求做类似的事情。

def exceptionHandler(id: UUID) = ExceptionHandler {
  case t =>
    val error = ErrorMessage(id.toString, 500, "Internal server error.")
    complete((InternalServerError, error))
}

def rejectionHandler(id: UUID) = RejectionHandler.newBuilder()
  .handleNotFound {
    val error = ErrorMessage(id.toString, 404, "Not found.")
    complete((NotFound, error))
  }
  .result()

def logRequestTimeRoutes(): Route = { ctx =>
  val id = UUID.randomUUID()
  val start = System.currentTimeMillis()
  // handling rejections/exceptions here so that we get proper status codes
  val innerRejectionsHandled = handleRejections(rejectionHandler(id))(routes(id))
  val innerExceptionsHandled = handleExceptions(exceptionHandler(id))(innerRejectionsHandled)
  mapResponse { resp =>
    // logRequestTime(id, end-start)
    resp
  }(innerExceptionsHandled)(ctx)
}

def routes(id: UUID) = {
  path("some" / "path") {
    get {
      val future = ??
      onSuccess(future) {
        case result => complete(result)
      }
    }
  }
}

是否可以通过请求生命周期传递自定义对象或将其注入RequestContext,以便我可以在exceptionHandler或rejectionHandler中提取类似的内容。

val exceptionHandler = ExceptionHandler {
  case t =>
    extractMyCustomObject { obj =>
      val error = ErrorMessage(obj.id.toString, 500, "Internal server error.")
      complete((InternalServerError, error))
    }
}

我使用的是akka版本" 2.4.7"

0 个答案:

没有答案