logRequest

logRequest

§Signature

  1. def logRequest(marker: String)(implicit log: LoggingContext): Directive0
  2. def logRequest(marker: String, level: LogLevel)(implicit log: LoggingContext): Directive0
  3. def logRequest(show: HttpRequest => String)(implicit log: LoggingContext): Directive0
  4. def logRequest(show: HttpRequest => LogEntry)(implicit log: LoggingContext): Directive0
  5. def logRequest(magnet: LoggingMagnet[HttpRequest => Unit])(implicit log: LoggingContext): Directive0

The signature shown is simplified, the real signature uses magnets. [1]

[1]See The Magnet Pattern for an explanation of magnet-based overloading.

§Description

Logs the request using the supplied LoggingMagnet[HttpRequest => Unit]. This LoggingMagnet is a wrapped function HttpRequest => Unit that can be implicitly created from the different constructors shown above. These constructors build a LoggingMagnet from these components:

  • A marker to prefix each log message with.
  • A log level.
  • A show function that calculates a string representation for a request.
  • An implicit LoggingContext that is used to emit the log message.
  • A function that creates a LogEntry which is a combination of the elements above.

It is also possible to use any other function HttpRequest => Unit for logging by wrapping it with LoggingMagnet. See the examples for ways to use the logRequest directive.

Use logResult for logging the response, or logRequestResult for logging both.

§Example

  1. // different possibilities of using logRequest
  2.  
  3. // The first alternatives use an implicitly available LoggingContext for logging
  4. // marks with "get-user", log with debug level, HttpRequest.toString
  5. DebuggingDirectives.logRequest("get-user")
  6.  
  7. // marks with "get-user", log with info level, HttpRequest.toString
  8. DebuggingDirectives.logRequest(("get-user", Logging.InfoLevel))
  9.  
  10. // logs just the request method at debug level
  11. def requestMethod(req: HttpRequest): String = req.method.name
  12. DebuggingDirectives.logRequest(requestMethod _)
  13.  
  14. // logs just the request method at info level
  15. def requestMethodAsInfo(req: HttpRequest): LogEntry = LogEntry(req.method.name, Logging.InfoLevel)
  16. DebuggingDirectives.logRequest(requestMethodAsInfo _)
  17.  
  18. // This one doesn't use the implicit LoggingContext but uses `println` for logging
  19. def printRequestMethod(req: HttpRequest): Unit = println(req.method.name)
  20. val logRequestPrintln = DebuggingDirectives.logRequest(LoggingMagnet(_ => printRequestMethod))
  21.  
  22. // tests:
  23. Get("/") ~> logRequestPrintln(complete("logged")) ~> check {
  24. responseAs[String] shouldEqual "logged"
  25. }