构造器将在哪个控制器中执行

时间:2018-07-18 12:19:55

标签: scala playframework

我有动作生成器

  class LoggingAction @Inject()(parser: BodyParsers.Default)(implicit ec: ExecutionContext) extends ActionBuilderImpl(parser) {
     override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = {
        Logger.info(s"Controller = ${},  " +
            s"method = ${request.method},  " +
            s"URI = ${request.uri},  " +
            s"remote-address = ${request.remoteAddress},  " +
            s"domain = ${request.domain}")
       block(request)
    }
   }
  }

我有一些简单的路线,其中之一

...
def index() = loggingAction { implicit request: Request[AnyContent] =>
Ok(views.html.index())
}
...

如何记录在LogginAction中此控制器中已执行LoggingAction的情况

1 个答案:

答案 0 :(得分:0)

您可以更改LoggingAction的签名以通过当前类。

 class LoggingAction @Inject() (controller: AbstractController)(parser: BodyParsers.Default)(implicit ec: ExecutionContext) extends ActionBuilderImpl(parser) {
     override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = {
        Logger.info(s"Controller = ${controller.getClass.getName},  " +
            s"method = ${request.method},  " +
            s"URI = ${request.uri},  " +
            s"remote-address = ${request.remoteAddress},  " +
            s"domain = ${request.domain}")
       block(request)
    }
   }

,然后为您的控制器创建日志记录操作的实例(可以通过为其创建Guice工厂来简化此操作)

class TestController @Inject() (cc: ControllerComponents, parser: BodyParsers.Default)(implicit ec: ExecutionContext)
  extends AbstractController(cc) {

  lazy val loggingAction = new LoggingAction(this, parser)

  def index ()= loggingAction { implicit request =>
    Ok(views.html.index())
  }
}