Skip to content

Instantly share code, notes, and snippets.

@feoktant
Created May 19, 2020 08:45
Show Gist options
  • Save feoktant/148688fd4d37a845acbdc7ee4f97ad8b to your computer and use it in GitHub Desktop.
Save feoktant/148688fd4d37a845acbdc7ee4f97ad8b to your computer and use it in GitHub Desktop.
Logging request as cUrl
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.directives.{DebuggingDirectives, LoggingMagnet}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.Materializer
import org.slf4j.Logger
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
trait LoggingUtils {
implicit def ec: ExecutionContext
implicit def mat: Materializer
def requestAsCurlString(req: HttpRequest): Future[String] =
Unmarshal(req.entity).to[String]
.map { body =>
val entries = s"--request ${req.method.value} '${req.uri}'" ::
s"--header 'Content-Type: ${req.entity.contentType}'" ::
req.headers.map(h => s"--header '$h'").toList :::
s"--data-raw '$body'" ::
Nil
"curl " + entries.mkString(" \\\n")
}
def printRequestMethod(log: Logger)(req: HttpRequest): Unit = {
requestAsCurlString(req).onComplete {
case Success(value) => log.info("Request in cUrl form is:\n{}", value)
case Failure(exception) => log.error("Unable to log request", exception)
}
}
def withLogging(log: Logger): Directive0 =
DebuggingDirectives.logRequest(LoggingMagnet(_ => printRequestMethod(log)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment