Akka-http如何记录服务器错误响应?

时间:2016-09-21 07:24:09

标签: scala akka-http

我有一个用scala和akka-http构建的http服务器。有没有办法记录发送给客户端的错误响应?

1 个答案:

答案 0 :(得分:1)

您可以查看文档LogResult Directive

在这里,您可以找到文档中显示的相同剪切代码:

// different possibilities of using logResponse

// The first alternatives use an implicitly available LoggingContext for logging
// marks with "get-user", log with debug level, HttpResponse.toString
DebuggingDirectives.logResult("get-user")

// marks with "get-user", log with info level, HttpResponse.toString
DebuggingDirectives.logResult(("get-user", Logging.InfoLevel))

// logs just the response status at debug level
def responseStatus(res: RouteResult): String = res match {
  case RouteResult.Complete(x)          => x.status.toString
  case RouteResult.Rejected(rejections) => "Rejected: " + rejections.mkString(", ")
}
DebuggingDirectives.logResult(responseStatus _)

// logs just the response status at info level
def responseStatusAsInfo(res: RouteResult): LogEntry = LogEntry(responseStatus(res), Logging.InfoLevel)
DebuggingDirectives.logResult(responseStatusAsInfo _)

// This one doesn't use the implicit LoggingContext but uses `println` for logging
def printResponseStatus(res: RouteResult): Unit = println(responseStatus(res))
val logResultPrintln = DebuggingDirectives.logResult(LoggingMagnet(_ => printResponseStatus))

// tests:
Get("/") ~> logResultPrintln(complete("logged")) ~> check {
  responseAs[String] shouldEqual "logged"
}