0
votes

Trying to monitor performance of our Ktor backend application and are able to attach Elastic APM agent to it. Server is visible at Kibana dashboard as a service. But it's not creating transactions automatically for each incoming request. When we manually start a transaction and end it in a specific route, then only it is recording performance for that request. Is there another way to solve this situation?

Tried following approach

  1. Intercepted each request in setup phase and started a transaction, but could not end the transaction facing issue while intercepting the same call at the end.
  2. For each request in controller/route defined below piece of code and it is working.
    get("/api/path") {
        val transaction: Transaction = ElasticApm.startTransaction()
        try {
            transaction.setName("MyTransaction#getApi")
            transaction.setType(Transaction.TYPE_REQUEST)
            // do business logic and response
         } catch (e: java.lang.Exception) {
            transaction.captureException(e)
            throw e
         } finally {
            transaction.end()
         }  
    }
    

Adding below line for better search result for other developers.
How to add interceptor on starting and ending on each request in ktor. Example of ApplicationCallPipeline.Monitoring and proceed()
1

1 Answers

1
votes

You can use the proceed method that executes the rest of a pipeline to catch any occurred exceptions and finish a transaction:

intercept(ApplicationCallPipeline.Monitoring) {
    val transaction: Transaction = ElasticApm.startTransaction()
    try {
        transaction.setName("MyTransaction#getApi")
        transaction.setType(Transaction.TYPE_REQUEST)
        proceed() // This will call the rest of a pipeline
    } catch (e: Exception) {
        transaction.captureException(e)
        throw e
    } finally {
        transaction.end()
    }
}

Also, you can use attributes to store a transaction for a call duration (begins when the request has started and ends when the response has been sent).