Need Elastic APM support for Ktor backend server

Our team is trying to monitor performance of our Ktor (by Jetbrains) backend application. We are able to attach Elastic APM agent in backend server, and this server is visible at Kibana dashboard as service. But it is not creating transaction 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. Please help if someone tried this earlier and was able to analyse all request without manual transaction of Elastic APM.
Reference code given below.

val transaction: Transaction = ElasticApm.startTransaction()
            try {
                transaction.setName("MyTransaction#getApi")
                transaction.setType(Transaction.TYPE_REQUEST)
                // do your thing...
        
            } catch (e: java.lang.Exception) {
                transaction.captureException(e)
                throw e
            } finally {
                transaction.end()
            }

Hi @Mahesh09 ,

I'm not familiar with Ktor, but it seems that it provides a way to intercept routes, which allows to implement a generic wrapper for all incoming transactions: Intercepting Routes | Ktor.

1 Like

You are right I am able to intercept and record every request by using interceptor.

hi @Mahesh09 ,
i'm also having this problem, can you show me how you did it?
thank you

ok, found the way..

routeWithMonitor.intercept(ApplicationCallPipeline.Features) {
        val transaction: Transaction = ElasticApm.startTransaction()
        try {
            transaction.setName("${context.request.httpMethod.value} ${context.request.uri}")
            transaction.setType(Transaction.TYPE_REQUEST)

            proceed()

        } finally {
            transaction.end()
        }
    }

and call it like this

routing{
    monitor {
        ...
    }
}

but the drawback is i need to setup transaction information manually,
next thing i need to find is to record request body and response status code.. or can we automate it?

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.