withLog

Signature

def withLog(log: LoggingAdapter): Directive0

Description

Allows running an inner route using an alternative LoggingAdapterLoggingAdapter in place of the default one.

The logging adapter can be extracted in an inner route using extractLog directly, or used by directives which internally extract the materializer without surfacing this fact in the API.

Example

Scala
sourceval special = Logging(system, "SpecialRoutes")

def sample() =
  path("sample") {
    extractLog { implicit log =>
      complete {
        val msg = s"Logging using $log!"
        log.debug(msg)
        msg
      }
    }
  }

val route =
  pathPrefix("special") {
    withLog(special) {
      sample() // `special` logging adapter will be used
    }
  } ~ sample() // default logging adapter will be used

// tests:
Get("/sample") ~> route ~> check {
  responseAs[String] shouldEqual s"Logging using ${system.log}!"
}
Get("/special/sample") ~> route ~> check {
  responseAs[String] shouldEqual s"Logging using $special!"
}
Java
sourceimport static akka.http.javadsl.server.Directives.withLog;

final LoggingAdapter special = Logging.getLogger(system(), "SpecialRoutes");

final Route sample = path("sample", () ->
  extractLog(log -> {
    final String msg = "Logging using " + log + "!";
    log.debug(msg);
    return complete(msg);
  }
  )
);

final Route route = Directives.concat(
  pathPrefix("special", () ->
    withLog(special, () -> sample)
  ),
  sample
);

// tests:
testRoute(route).run(HttpRequest.GET("/sample"))
  .assertEntity("Logging using " + system().log() + "!");

testRoute(route).run(HttpRequest.GET("/special/sample"))
  .assertEntity("Logging using " + special + "!");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.