Search code examples
scalaplayframeworkcodahale-metrics

Unable to create timer play metrics on API basis


I am creating Play metrics on API basis, So for that i have a filter which will identify the URL from request header and create metrics on the basis of URL. But for creating timer metrics we have to start and stop the context at the beginning and end of method respectively.

So in my custom filter it is starting the context but i need to figure out how to stop it as API call is not giving response back through filter. Only Request is going though filter but response is going through controller.

Need Help to understand how can i achieve metrics on API basis through play filters. Any leads will be lauded.

What achieved so far:

val getWallets = metrics.defaultRegistry.meter("GetWallets") // val lockWallet = metrics.defaultRegistry.meter("LockWallet") 

override def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
  requestHeader.uri match {
    case IConstant.GET_WALLETS => { 
      getWallets.mark()
      nextFilter(requestHeader)
    }
    case _ => { 
      nextFilter(requestHeader)
    }
  }
}

Solution

  • Given the signature of the Filter.apply:

    override def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result]
    

    this method will return a Future[Result].

    So you could map over the Future once completed to stop the metric, like below:

    override def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
      requestHeader.uri match {
        case IConstant.GET_WALLETS => { 
          getWallets.mark()
          nextFilter(requestHeader).map { result =>
    
            // Stop the metric here
    
            result
          }
        }
        case _ => { 
          nextFilter(requestHeader)
        }
      }
    }